1

我有 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 表中并被添加到Bar BarId表中。

如果在 fluent API 配置中UniqueFooBar,我改为尝试使用 Foo 的“名称”属性,则该字段已存在的错误。如果我尝试使用 Bar 的“Id”属性,也会发生同样的情况。

如何将 UniqueFooBar 配置为具有 FKFoo.NameBar.Id一对一关系?

更新

  • 既没有Foo也没有Bar约束或要求 a UniqueFooBar
  • UniqueFooBar 记录需要 aFooName和 aBarId

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

4

1 回答 1

1

取自这里,下面是一个示例,说明如何实现两个实体之间的一对一映射,将其推断为链接表,并根据需要添加 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);
    }
}
于 2013-09-04T08:22:30.520 回答