Linq to实体插入EF 1

时间:2009-12-29 17:04:38

标签: c# .net entity-framework linq-to-entities

我有2个实体:人(Id,CategoryId)和类别(Id)。

现在,当我尝试插入一个只有Id和CategoryId的新Person时,会抛出一个关于与Category有关系的Person的异常。

以下代码不起作用:

Person newPerson = new Person();
newPerson.Id = 1;
newPerson.CategoryId = 1;
context.AddToPersonSet(newPerson);
context.SaveChanges

此代码有效

Person newPerson = new Person();
newPerson.Id = 1;
newPerson.Category = context.CategorySet.Where(cat=> cat.Id == 1).First(); 
newPerson.CategoryId = 1;
context.AddToPersonSet(newPerson);
context.SaveChanges

是否有其他方式可以插入而无需获取类别实体?

2 个答案:

答案 0 :(得分:2)

在带有FK关联的EF 4中,你的第一个代码将“正常工作”,所以我假设你正在使用EF 1,尽管你没有说。

EF 1的解决方法是:

Person newPerson = new Person();
newPerson.Id = 1;
// substitute the correct strings for your mapping.
newPerson.CategoryReference.EntityKey = 
    new EntityKey("MyEntities.Categories", "CategoryId", 1);
context.AddToPersonSet(newPerson);
context.SaveChanges();

您不应该在EF 1中Person.CategoryId映射 。它甚至不应该是Person类型的一部分。

显然,最好的解决方案是使用EF 4.但如果这不是一个选项,上述工作正常。

答案 1 :(得分:1)