实体框架代码优先 - 忽略基类

时间:2012-01-18 02:49:34

标签: asp.net c#-4.0 entity-framework-4.1 ef-code-first

我的模型如下:

public class User : System.Web.Security.MembershipUser
{
public int UserId { get; set; }
    public string SomeProperty { get; set; }
}

生成我的数据库时,我希望实体框架忽略MembershipUser,只生成一个名为User的表,其中包含User类中的两个属性。我试过以下无济于事。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Ignore<System.Web.Security.MembershipUser>();
}

2 个答案:

答案 0 :(得分:8)

您有两种选择。一种方法是通过为每个属性调用Ignore来忽略所有基类属性。

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
}

其他选项是使用合成从MembershipUser类中检索User实例。此User不会从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
        }
    }
}

并映射如下

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().Ignore(u => u.MembershipUser);
    modelBuilder.Ignore<System.Web.Security.MembershipUser>();

}

答案 1 :(得分:2)

NotMappedAttribute属性是你的朋友:

[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; }
    }
}

我不确定代码是否会首先自动处理元数据,尝试上述操作,如果不起作用,请手动附加元数据(即取消注释注释行)。

<强>更新 我更喜欢上述解决方案,但如果它对你来说太冗长,请使用StructuralTypeConfiguration<TStructuralType>.Ignore<TProperty> Method方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    var config = modelBuilder.Entity<User>();
    config.Ignore(u => u.UserName);
}