Entity Framework 4.1 Code First - 如何在两个表之间创建两种不同的关系
我需要创建一个关系,其中有一个链接到地址表的用户表。问题是我需要地址表来存储历史地址。用户也可能根本没有地址。
public class user
{
public virtual int ID { get; set; }
...
public virtual int? AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Address CurrentAddress { get; set; }
public virtual ICollection<Address> HistoricAddresses { get; set; }
}
public class Address
{
public virtual int ID { get; set; }
...
}
我尝试了各种方法来使其正常工作,但遇到了各种错误,例如在 User 和 Address: 之间放置另一个表
public class HistoricAddress
{
public virtual int ID { get; set; }
public Address HistoricAddress { get; set; }
}
public class user
{
public virtual int ID { get; set; }
public virtual Address CurrentAddress { get; set; }
public virtual ICollection<HistricAddress> HistoricAddresses { get; set; }
...
}
以及各种其他方法,但这也会引发错误。必须有一个正确的方法来做到这一点。我得到的最后一个错误是:
“System.Data.Entity.Infrastruct.DbUpdateException:更新条目时发生错误。有关详细信息,请参阅内部异常。 ---> System.Data.UpdateException:更新条目时发生错误有关详细信息,请参阅内部异常。 ---> System.InvalidOperationException:ReferentialConstraint 中的依赖属性映射到存储生成的列:“ID”。
I need to create a relationship where I have a user table that links to an address table. The problem is that I need the address table to also store historic addresses. It is also possible that a user might not have an address at all.
public class user
{
public virtual int ID { get; set; }
...
public virtual int? AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Address CurrentAddress { get; set; }
public virtual ICollection<Address> HistoricAddresses { get; set; }
}
public class Address
{
public virtual int ID { get; set; }
...
}
I tried various ways to get this to work and got various errors like putting another table between User and Address:
public class HistoricAddress
{
public virtual int ID { get; set; }
public Address HistoricAddress { get; set; }
}
public class user
{
public virtual int ID { get; set; }
public virtual Address CurrentAddress { get; set; }
public virtual ICollection<HistricAddress> HistoricAddresses { get; set; }
...
}
and various other ways, but this also throws up errors. There must be a proper way of doing this. The last error I got was:
"System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.InvalidOperationException: A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'ID'."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 3 个表来映射以下模型。
重写自定义
DbContext
的OnModelCreating
方法创建的表是
You can map the following model with 3 tables.
Override the
OnModelCreating
method of your customDbContext
Tables created are