【发布时间】:2011-02-22 19:36:52
【问题描述】:
我有一个 POCO 类,它与另一个类有两个单向一元关系,两个类共享一个祖先。生成的架构中的外键名称不反映属性名称。 (属性 MainContact 和 FinancialContact 给出 PersonId 和 PersonId1 字段名称)。
如何影响架构生成以生成与属性名称匹配的数据库列名称?
模型如下所示:
代码如下所示:
public class CustomerContext: DbContext
{
public DbSet<Organisation> Organisations { get; set; }
public DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
DbDatabase.SetInitializer(new DropCreateDatabaseAlways<CustomerContext>());
}
}
public abstract class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Person : Customer
{
public string Email { get; set; }
}
public class Organisation : Customer
{
public Person FinancialContact { get; set; }
public Person MainContact { get; set; }
}
架构如下所示:
druttka 的回答
druttka 在下面的回答完成了这项工作,很高兴知道这是一个 CTP5 错误。 EF 还需要指定级联行为,我按照 druttka 给出的链接中的示例使用 fluent API 来执行此操作。 Morteza Manavi here 的更多好读物。
现在的代码是这样的:
public class CustomerContext : DbContext
{
public DbSet<Organisation> Organisations { get; set; }
public DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
DbDatabase.SetInitializer(new DropCreateDatabaseAlways<CustomerContext>());
builder.Entity<Organisation>()
.HasRequired(p => p.MainContact)
.WithMany()
.HasForeignKey(p => p.MainContactId)
.WillCascadeOnDelete(false);
builder.Entity<Organisation>()
.Property(p => p.MainContactId)
.HasColumnName("MainContact");
builder.Entity<Organisation>()
.HasRequired(p => p.FinancialContact)
.WithMany()
.HasForeignKey(p => p.FinancialContactId)
.WillCascadeOnDelete(false);
builder.Entity<Organisation>()
.Property(p => p.FinancialContactId)
.HasColumnName("FinancialContact");
}
}
public abstract class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Person : Customer
{
public string Email { get; set; }
}
public class Organisation : Customer
{
public Person FinancialContact { get; set; }
public int FinancialContactId { get; set; }
public Person MainContact { get; set; }
public int MainContactId { get; set; }
}
现在提供了更合适的数据库:
【问题讨论】:
-
使用属性来反映你的数据库模式命名不当?
-
让我知道我的答案中的 EDIT 2 是否适合您。正如我所说,我测试了数据库是否按预期创建,但没有测试进一步的 CRUD 操作,所以我很想知道它是否正常运行。
标签: c# entity-framework code-first