0
我有一个问题。在实体框架上使用流畅的api映射实体5
我有这两个表:
主要表是用户与顾客的依赖。
反向工程师第一代码生成的类如下:
public class User
{
public User()
{
this.Customers = new List<Customer>();
}
...
public virtual ICollection<Customer> Customers { get; set; }
}
public class Customer
{
public Customer()
{
}
...
public int UserID { get; set; }
public virtual User User { get; set; }
}
我发在用户类以下修改:
public class User
{
public User()
{
}
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
}
由于关系是1对零或 - 一。
原来的映射是这样的:
// Relationships
this.HasRequired(t => t.User)
.WithMany(t => t.Customers)
.HasForeignKey(d => d.UserID);
而且修改后的映射是这样的:
this.HasRequired(t => t.User)
.WithOptional(t => t.Customer)
.Map(m => m.MapKey("UserID"));
是正确的? 如果不是,这个映射将如何?
谢谢。
嗨@Slauma,我不明白为什么删除customer表的外键。我在这个例子中做了他的第二个选择。 – Gus
@格斯:不,这不是他的第二选择。他的第二个选择(“一对一外键协会”)使用'WithMany()',而不是'WithOptional'。这是与已移除集合的一对多关系,即只有一个导航属性。另外,如果您有一个名为UserID的属性,则不能使用MapKey(“UserID”)。那么你必须使用'HasForeignKey',就像Mortezza的例子所示。 – Slauma
嗨@Slauma,谢谢你的帮助。 – Gus