我有3个实体:
Foo
Bar
UniqueFooBar
Foo
和Bar
是如下实体:
public class Bar {
public int Id {get; set;}
// inverse nav property
public virtual UniqueFooBar UniqueFooBar {get; set;}
}
public class Foo {
public string Name {get; set;}
// inverse nav property
public virtual UniqueFooBar UniqueFooBar {get; set;}
}
UniqueFooBar
的查询如下:
public class UniqueFooBar {
public string FooName {get; set;}
public int BarId {get; set;}
// nav properties
public virtual Foo Foo {get; set;}
public virtual Bar Bar {get; set;}
}
有限制:
Foo
是唯一的Foo
和Bar
Foo
名称是PK
流畅的API如下:
class UniqueFooBarConfiguration : EntityTypeConfiguration<UniqueFooBar> {
public UniqueFooBarConfiguration() {
// Define the tablename and schema
Map(entity => entity.ToTable("UniqueFooBars"));
//// Define non-conventional key
HasKey(fooBar => fooBar.FooName);
// Define FKs - 1-to-1
HasRequired(fooBar => fooBar.Foo)
.WithRequiredPrincipal(foo => foo.UniqueFooBar)
.Map(key => key.MapKey("FooName"));
HasRequired(fooBar => fooBar.Bar)
.WithRequiredPrincipal(bar => bar.UniqueFooBar)
.Map(key => key.MapKey("BarId"));
// --------------------------------
}
}
正在发生的事情是将FooName
添加到Foo表格中并将 BarId
添加到条形码表中。
如果在UniqueFooBar
的流畅API配置中,我尝试使用Foo的“Name”属性,则会出现该字段已存在的错误。如果我尝试使用Bar的“Id”属性,也会发生同样的情况。
如何配置UniqueFooBar以使FK与Foo.Name
和Bar.Id
成为一对一的关系?
更新
Foo
和Bar
都没有UniqueFooBar
的约束或要求。FooName
和BarId
这似乎与How to declare one to one relationship using Entity Framework 4 Code First (POCO)
不同答案 0 :(得分:1)
从here获取,下面是如何在两个实体之间实现一对一映射的示例,为链接表推断这一点,根据需要添加HasRequired。
可以在没有lambda的情况下指定WithRequiredPrincipal,这允许您排除导航属性并仍然获得正确的一对一映射。
在OnModelCreating方法的覆盖中,您可以使用DBModelBuilder参数定义关系。
public class Customer
{
public Customer()
{
Address = new Address();
}
public Guid Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public Guid Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Street { get; set; }
}
public class CustomerContext : DbContext
{
public IDbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasRequired(x => x.Address)
.WithRequiredPrincipal();
base.OnModelCreating(modelBuilder);
}
}