我使用实体框架4.1。我有一个正常的模型。edmx,它将Match类映射到'Match'数据库表,这可以正常使用EF访问。
然而,我需要自定义的属性方法的匹配,所以我扩展了这个使用部分类,我可以添加我的属性等。
所有这些都工作得很好,但是我只是不知道如何通过主键/id实例化我的部分匹配类的实例。也就是说,我可以将Id传递给构造函数,并使用数据库中的所有数据填充对象。
我知道我们可以做以下操作来从调用代码填充:
public Match PopulateforMatchId(int matchId)
{
var match = (from m in _db.Matches
.Include("TeamA")
.Include("TeamB")
.Include("Season")
.Include("Season.Competition")
where m.Match_ID == matchId
select m).FirstOrDefault();
return match;
}
然而,这不是我所需要的,因为这不是分部类本身的自包含,我需要它填充自己,因为分部类中的其他属性依赖于对象本身,在它们可以计算之前具有其数据。
有谁知道我该怎么做吗?
感谢凯文这是使用实体框架的错误方式。实体框架不适合简单地填充现有对象。此外,它要求实体对EF上下文具有内部依赖性。
如何让它工作(但我绝对不推荐):
public Match(int matchId)
{
// You called constructor yourselves = you have unproxied entity without
// dynamic change tracking and without lazy loading
Id = matchId;
// I'm not sure if this is possible in entity constructor but generally it should work
// Get context somewhere - service locator pattern
ObjectContext context = ContextProvider.GetCurrent();
context.Matches.Attach(this);
context.Refresh(RefreshMode.StoreWins, this);
// Now you should have populated Match entity itself but not its navigation properties
// To populate relations you must call separate query for each of them because `Include`
// is possible only when the entity is created and loaded by EF and lazy loading is off
// in this case
context.LoadProperty(this, m => m.TeamA);
context.LoadProperty(this, m => m.TeamB);
Season = (from s in context.Seasons.Include("Competition")
select s).ToList();
}
这也是错误构造函数的例子——构造函数不应该采用如此沉重的逻辑。它应该由其他一些初始化方法负责