Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First - Ignore Base Class

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>();
}
like image 464
Mark Avatar asked Jan 18 '12 02:01

Mark


2 Answers

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>();

}
like image 111
Eranga Avatar answered Sep 22 '22 01:09

Eranga


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);
}
like image 20
Shimmy Weitzhandler Avatar answered Sep 23 '22 01:09

Shimmy Weitzhandler