代码首先CTP4 - 1:1 - 目前是否支持相同的PK / FK? [英] Code first CTP4 - 1:1 - Is same PK/FK currently supported?
问题描述
所以我已经想出如果第二个表同时拥有主键和外键,如何进行一对一/零映射。
So I've figured out how to do a one to one/zero mapping if the second table has both a primary key and a foreign key.
但当然在我们现有的数据库中,对于辅助表(读取EmployeeDetails或CustomerDetails),此(辅助或详细信息)表的主键也是外键 - 即我们使用主表中使用的相同主键(读取Employees /客户
表)。
But of course in our existing database, for the secondary table (read EmployeeDetails or CustomerDetails), the primary key of this (secondary or details) table is also the foreign key - i.e. we use the same primary key as used in the main table (read Employees/Customer table).
首先是CTP4代码目前是否支持此方案?我还没弄明白如何让这个场景发挥作用(我认为这是一个简单的案例!)
Is this scenario currently supported by the code first CTP4? I have yet to figure out how to get this scenario to work (and I thought this was a simple case!)
谢谢
Myles 。
推荐答案
Hi Myles,
Hi Myles,
是的,这是支持的。以下是一些示例代码:
Yes, this is supported. Here is some sample code:
public class CustomerContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<CustomerDetail> CustomerDetails { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerDetail>()
.HasKey(d => d.CustomerId);
modelBuilder.Entity<CustomerDetail>()
.Property(d => d.CustomerId)
.StoreGeneratedPattern = System.Data.Metadata.Edm.StoreGeneratedPattern.None;
modelBuilder.Entity<Customer>()
.HasRequired(c => c.Detail)
.WithRequiredPrincipal(d => d.Customer)
.HasConstraint((d, c) => d.CustomerId == c.CustomerId);
}
}
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public virtual CustomerDetail Detail { get; set; }
}
public class CustomerDetail
{
public int CustomerId { get; set; }
public string Detail { get; set; }
public virtual Customer Customer { get; set; }
}
这篇关于代码首先CTP4 - 1:1 - 目前是否支持相同的PK / FK?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!