使用EF6.0 & .NET 4.5。 我有一大堆的部分扩展我的框架对象。连接没有上下文的实体框架对象?
一个人有多辆车。这些车有一个模型/品牌(其它汽车共享):
table person: id, name, whatever, ..
table car: id, personId, modelId, hasCrashedManyTimes, ..
table model: id, brand, model, hasWheels, hasEngine, ..
在我的主程序我做
using(var db = My.EntityContext()) // get connection from pool
{
var person = new person();
person.cars.Add(new car("Ford", "Focus"));
db.persons.Add(person);
db.SaveChanges();
}
对象 '车' 扩展
public car(string brand, string model) : this()
{
using(var db = My.EntityContext()) {
this.model = db.models.FirstOrDefault(m => m.brand == brand && m.model == model)
if(this.model == null) this.model = new model() { brand = brand, model = model };
}
}
这工作,但我没有想到的是'模型'每次都被添加。我搜索和应用的模型不是“附加”的。
有人明白我在做什么吗? 为什么会发生这种情况,以及如何正确执行此操作?
但是,对于现有的模型,它被提取(1st),而不是创建(2th)。因此,如果它被连接,它为什么还在我的数据库中添加一个新的模型(具有相同的属性)? –