[英]Configure one-to-one relationship with EF Fluent API
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public string Description { get; set; }
}
So I want a one-to-one relationship between Person
and Category
. 所以我想要Person
和Category
之间一对一的关系。
Person
must have Category
(FK). Person
必须具有Category
(FK)。 Category
will throw Exception if some of the CategoryID
still exists in Person
table. 删除Category
如果某些会抛出异常CategoryID
仍然存在于Person
表。 How to achieve this with EF FluentAPI? 如何使用EF FluentAPI实现这一目标?
My current code : 我当前的代码:
modelBuilder.Entity<Person>()
.HasKey(pk => pk.PersonID)
.HasRequired(r => r.CategoryID);
Take a look at this MSDN documentation on creating relationships with FluentAPI 看一下有关使用FluentAPI创建关系的 MSDN文档
Since the navigation property is only defined on the person object you would go with this: 由于导航属性仅在人员对象上定义,因此您可以这样做:
modelBuilder.Entity<Person>()
.HasRequired(t => t.Category)
.WithRequiredPrincipal();
use this : 用这个 :
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public string Description { get; set; }
public virtual Person Person{ get; set; }
}
and with fluent api : 并使用流利的api:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasRequired(c => c.Category)
.WithOptional(c => c.Person)
.WillCascadeOnDelete(false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.