[英]How to make One-To-One relationship with existing fields?
我有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
添加到Bar表中。
如果在UniqueFooBar
的流暢API配置中,我改為嘗試使用Foo的“ Name”屬性,那么該字段已經存在錯誤。 如果我嘗試使用Bar的“ Id”屬性,也會發生同樣的情況。
如何配置UniqueFooBar以將FK與Foo.Name
和Bar.Id
進行一對一關系?
更新
Foo
和Bar
都沒有對UniqueFooBar
約束或要求。 FooName
和BarId
下面是從此處獲取的示例,該示例說明了如何實現兩個實體之間的一對一映射,將其推斷出一個鏈接表,並根據需要添加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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.