我的数据库中有以下两个表:
地址:
Street1
City
State
Zipcode
客户:
Name
LocationAddressId (FK to Address table)
MailingAddressId (FK to address table)
我为此生成了一个实体框架模型。当我创建客户对象并仅填充LocationAddress
而不填充MailingAddress
时,会为LocationAddress
生成id(地址表的主键)。此ID已分配给LocationAddressId
,同样的ID也会分配给MailingAddressId
。
这是我的代码:
Customer c = new Customer();
var a = new Address
{
Street1 = "Test",
City = "test",
Zip = "43343",
Country = "sdf",
};
c.Address = a;
c.Name = "Test Customer";
ctx.Customers.AddObject(c);
ctx.SaveChanges();
保存更改后,即使我没有为邮件地址分配任何内容,c.LocationAddressId
和c.MailingAddressId
也是相同的。
问题#2:
在我的代码中,当我尝试创建MailingAddress
时,我收到错误
“无法确定主要目标 'TestModel.FK_Customer_LocationAddress_Address'的关系。多 添加的实体可能具有相同的主键。
这是我的代码:
Customer c = new Customer();
var a = new Address
{
Street1 = "Test",
City = "test",
Zip = "43343",
Country = "sdf",
};
c.Address = a;
var b = new Address
{
Street1 = "Test mailing addr",
City = "test",
Zip = "43343",
Country = "sdf",
};
c.Address1 = b;
c.Name = "Test Customer";
ctx.Customers.AddObject(c);
ctx.SaveChanges();
我不确定我是否以正确的方式创建对象。有没有人对导致问题的原因有任何想法?
由于