【发布时间】:2010-11-26 00:46:32
【问题描述】:
我无法使用 EntityFramework 将我的实体保存到数据库中。我必须要表、播放器和地址。 Player 表通过 AddressId 外键关系引用了 Address 表。所以 Player.AddressId 指向 Address.AddressId。
现在在调用以下代码时,我收到一条错误消息:“ReferentialConstraint 中的依赖属性被映射到存储生成的列”
public override int CreatePlayer(BizObjects.Player player)
{
var entity = new EntityFramework.Player();
entity.PlayerId = player.PlayerId;
entity.FirstName = player.FirstName;
entity.LastName = player.LastName;
entity.Gender = player.Gender;
entity.BirthDate = player.BirthDate;
entity.DisplayAge = player.DisplayAge;
entity.Level = player.Level;
entity.PlayingHand = player.PlayingHand;
entity.BackhandType = player.BackhandType;
entity.PlayingStyle = player.PlayingStyle;
entity.Description = player.Description;
entity.UserId = player.UserId;
entity.Address = new Address();
entity.Address.AddressId = player.Address.AddressId;
entity.Address.Line1 = player.Address.Line1;
entity.Address.Line2 = player.Address.Line2;
entity.Address.City = player.Address.City;
entity.Address.State = player.Address.State;
entity.Address.ZipCode = player.Address.ZipCode;
_entities.AddToPlayer(entity);
_entities.SaveChanges();
return entity.PlayerId;
}
我是使用 EF 的新手。任何指针都非常感谢。
【问题讨论】:
-
两个问题:Player.Address.AddressId的值是否大于零? Address.AddressId 是基于整数的 IDENTITY 列吗?
-
Address.AddressId 是自动递增的整数标识列。在提供的代码实现中,Player.Address.AddressId 为 null,因为尚未创建地址。
-
我想我不确定是否通过创建 Player 实体也会创建 Address 实体,因为这两个表都是相关的。我想知道使用 EF 保存相关表的最佳方法是什么。
-
好的,那么在哪一行抛出异常?
-
什么是 Player.UserId 属性?这是某种外键吗?
标签: asp.net-mvc entity-framework