我有两个类Queries和ContactRepository。
public static class Queries
{
public static Contact GetContactByName(CEntities context, string name)
{
return (from Contact c in context.Contacts
where c.Name == name
select c).FirstOrDefault();
}
}
public class ContactRepository
{
private CEntities _dbContext;
public ContactRepository()
{
_dbContext = new CEntities();
}
public void CreateContactAddress(string contactName, string address, string city, string state, string zip)
{
int contactId;
ContactAddress ca = new ContactAddress();
contactId = Queries.GetContactByName(_dbContext, contactName).Id;
ca.ContactId = contactId;
ca.Address = address
ca.City = city;
ca.State = state;
ca.Zip = zip;
_dbContext.ContactAddresses.AddObject(ca);
_dbContext.SaveChanges();
}
}
当我调用CreateContactAddress()时,SaveChanges()方法崩溃并出现以下错误:
无法确定有效的订购 对于从属操作。依赖 由于外键可能存在 约束,模型要求或 存储生成的值。
我可以将LINQ查询移动到CreateContactAddress()方法本身,一切都很完美。谁能解释一下发生了什么?