繁体   English   中英

如何与现有字段建立一对一关系?

[英]How to make One-To-One relationship with existing fields?

我有3个实体:

  • Foo
  • Bar
  • UniqueFooBar

FooBar是如下实体:

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是独一无二的
  • FooBar之间存在一对一的关系
  • 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.NameBar.Id进行一对一关系?

更新

  • FooBar都没有对UniqueFooBar约束或要求。
  • UniqueFooBar记录需要FooNameBarId

这似乎与如何使用Entity Framework 4 Code First(POCO)声明一对一关系不同

下面是从此处获取的示例,该示例说明了如何实现两个实体之间的一对一映射,将其推断出一个链接表,并根据需要添加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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM