开发者

CodeFirst EF 4.1 Inheritance - Renaming PK/FK

I have two classes, ThreadItem and Enquiry.

public class ThreadItem
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }
} 

public class ThreadItemMapping : EntityTypeConfiguration<ThreadItem>
{
    public ThreadItemMapping()
    {
        Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnName("ThreadItemId");
    }
}

[Table("Enquiry")]
public class Enquiry : ThreadItem
{
    public string Comment { get; set;}
}

Now, this works, not a single problem. I have a [ThreadItem] table, and an [Enquiry] table. My Enquiry table has a PK/FK which is mapped to ThreadItem, which is what I need. However, I would like to rename the column.

Currently is it [ThreadItemId], as per开发者_高级运维 the ThreadItemMapping class. I Would like to re-name it [EnquiryId]. I understand that it being called [ThreadItemId] makes sense, this is more of a 'is it possible' question to be honest.

Any ideas?

Cheers, D


http://msdn.microsoft.com/en-us/library/gg197525%28v=vs.103%29.aspx

I'm not saying it cannot be done, but these examples don't show such a thing being done.

If you use Fluent-API conventions, however, it's quite simple.

Your POCO definitions:

public class BaseClass
{
    public int Id {get; set;}
}

public class DerivedClass : BaseClass
{
    public string Data {get; set;}
}

Configuring the mappings to the DB:

public class BaseConfiguration : EntityTypeConfiguration<BaseClass>
{
    public BaseConfiguration()
{
    HasKey(k => k.Id);
    Property(p => p.Id).HasColumnName("Id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
}
}

public class DerivedConfiguration : BaseConfiguration
{
    public DerivedConfiguration()
{
    Property(p => p.Id).HasColumnName("BaseClassId");
}
}

putting it all together

public class MyContext : DbContext
{
    public MyContext(string connectionString) : base(connectionString)
{
    Database.SetInitializer<MyContext>(null);
}

public DbSet<BaseClass> Bases { get; set; }
public DbSet<DerivedClass> Deriveds { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new BaseConfiguration());
    modelBuilder.Configurations.Add(new DerivedConfiguration());
}
}

So you instantiate a MyContext passing in your connection string and the configurations tell EF how to relate to the tables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜