tah*_*ala 266 c# database-design entity-framework foreign-key-relationship
public class Foo
{
public string FooId{get;set;}
public Boo Boo{get;set;}
}
public class Boo
{
public string BooId{get;set;}
public Foo Foo{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
当我收到错误时,我试图在Entity Framework中执行此操作:
无法确定类型"ConsoleApplication5.Boo"和"ConsoleApplication5.Foo"之间关联的主要结束.必须使用关系流畅API或数据注释显式配置此关联的主要结尾.
我已经在StackOverflow上看到了有关此错误的解决方案的问题,但我想了解术语"主要结束"的含义.
Lad*_*nka 374
在一对一的关系中,一端必须是主要的,第二端必须是依赖的.主要末端是将首先插入的末端,并且可以在没有从属末端的情况下存在.从属端是必须在主体之后插入的端,因为它具有主体的外键.
如果实体框架FK依赖必须也是它的PK,所以在你的情况下你应该使用:
public class Boo
{
[Key, ForeignKey("Foo")]
public string BooId{get;set;}
public Foo Foo{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
或者流畅的映射
modelBuilder.Entity<Foo>()
.HasOptional(f => f.Boo)
.WithRequired(s => s.Foo);
Run Code Online (Sandbox Code Playgroud)
Len*_*rri 181
您还可以使用[Required]
数据注释属性来解决此问题:
public class Foo
{
public string FooId { get; set; }
public Boo Boo { get; set; }
}
public class Boo
{
public string BooId { get; set; }
[Required]
public Foo Foo {get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Foo
是必需的Boo
.
这是参考@Ladislav Mrnka关于使用流畅的api配置一对一关系的答案.
有一个FK of dependent must be it's PK
不可行的情况.
例如,Foo
已经有了一对多的关系Bar
.
public class Foo {
public Guid FooId;
public virtual ICollection<> Bars;
}
public class Bar {
//PK
public Guid BarId;
//FK to Foo
public Guid FooId;
public virtual Foo Foo;
}
Run Code Online (Sandbox Code Playgroud)
现在,我们必须在Foo和Bar之间添加另一个一对一的关系.
public class Foo {
public Guid FooId;
public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
public virtual Bar PrimaryBar;
public virtual ICollection<> Bars;
}
public class Bar {
public Guid BarId;
public Guid FooId;
public virtual Foo PrimaryBarOfFoo;
public virtual Foo Foo;
}
Run Code Online (Sandbox Code Playgroud)
以下是如何使用流畅的api指定一对一关系:
modelBuilder.Entity<Bar>()
.HasOptional(p => p.PrimaryBarOfFoo)
.WithOptionalPrincipal(o => o.PrimaryBar)
.Map(x => x.MapKey("PrimaryBarId"));
Run Code Online (Sandbox Code Playgroud)
请注意,虽然PrimaryBarId
需要删除添加,但我们通过流畅的api指定它.
另请注意,方法名称[WithOptionalPrincipal()][1]
具有讽刺意味.在这种情况下,Principal是Bar.msdn上的WithOptionalDependent()描述使其更加清晰.
归档时间: |
|
查看次数: |
115030 次 |
最近记录: |