I have a model as follows:
public class User : System.Web.Security.MembershipUser
{
public int UserId { get; set; }
public string SomeProperty { get; set; }
}
When my database is generated I want the Entity Framework to ignore MembershipUser and only generate a table named User with the two properties from the User class. I've tried the following to no avail.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Ignore<System.Web.Security.MembershipUser>();
}
There are two options for you. One is to ignore all the base class properties by calling Ignore
for each property.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Ignore(u => u.ProviderUserKey);
modelBuilder.Entity<User>().Ignore(u => u.LastActivityDate);
// and so on for all base class properties
}
Other option would be to use composition to retrieve a MembershipUser
instance from your User
class. Here User
class is not inherited from MembershipUser
.
public class User
{
public int UserId { get; set; }
public string SomeProperty { get; set; }
public MembershipUser MembershipUser
{
get
{
// create an instance using the available properties and return
}
}
}
And map as follows
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Ignore(u => u.MembershipUser);
modelBuilder.Ignore<System.Web.Security.MembershipUser>();
}
NotMappedAttribute
attribute is your friend:
[MetadataType(typeof(UserMd)]
public class User : System.Web.Security.MembershipUser
{
////read description bellow code
//static User()
//{
// var type = typeof(User);
// TypeDescriptor.AddProviderTransparent(
// new AssociatedMetadataTypeTypeDescriptionProvider(type), type);
//}
public int UserId { get; set; }
public string SomeProperty { get; set; }
internal class UserMd
{
[NotMapped]
public string UserName { get; set; }
}
}
I'm not sure if code first processes the metadata automatically by itself, try the above, and if it doesn't work, attach the metadata manually (i.e. uncomment the commented lines).
Update
I do like the above solution better, but if it's too verbose for you, use the StructuralTypeConfiguration<TStructuralType>.Ignore<TProperty> Method
method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var config = modelBuilder.Entity<User>();
config.Ignore(u => u.UserName);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With