【发布时间】:2021-07-29 15:30:41
【问题描述】:
所以我想将 1 到 1 的关系从一个表应用到另一个表,每个表都有导航属性,并且至少有一个模型可以访问外键。
假设这个例子
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public int ContactId { get; set; }
public virtual Contact Contact { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
}
modelBuilder.Entity<User>().HasOptional<Contact>(u=> u.Contact)
.WithRequired(c => c.User).Map(m => m.MapKey("ContactId")).
类似于此堆栈溢出问题中使用的相同示例:
EF Code First - 1-to-1 Optional Relationship
问题在于它给出了一个错误,指出属性名称“ContactId”已定义。
但我想在数据库和模型上都定义这个外部属性,以便我可以使用例如 linq:
this.dbContextProvider.CurrentContext.User.SingleOrDefault(src => src.ContactId == contactId);
或者这是可以接受的还是非常无能的:
this.dbContextProvider.CurrentContext.User.SingleOrDefault(src => src.Contact.Id == contactId);
这最后一个选项将在查询数据库时在两个表之间创建一个连接,对吧?
【问题讨论】:
-
不要对 ef 6 使用 modelbuilder。使用注释更容易:[ForeignKey("Contact")] above public int ContactId {get;set;}
-
@GHDevOps 可以使用数据注释完成的所有操作也可以使用 Fluent API / ModelBuilder 来实现。反之则不然。
标签: c# .net entity-framework entity-framework-6 ef-fluent-api