类似问题
实体类型 <classname> 不是当前上下文模型的一部分- 和 - EF 4.1 Code First 错误 - 实体类型 SomeType 不是当前上下文模型的一部分是类似的问题,但它们是“代码优先”的观点仅使用更简单的数据模型,并解决连接字符串和映射问题。请仔细看看这个。
症状
// HomeController.cs
public ActionResult Index()
{
var _db = new MealsContext();
var m = _db.Meals.ToList();
var d = _db.Drinks.ToList();
return View();
}
Drinks检索集合时引发异常:
The entity type Drink is not part of the model for the current context.
代码
// Meal.cs
public class Meal
{
public int Id { get; set; }
public string Stuff { get; set; }
public virtual ICollection<Meat> Meats { get; set; }
public virtual ICollection<Vegetable> Vegetables { get; set; }
}
// Meat.cs
public class Meat
{
public int Id { get; set; }
public string Name { get; set; }
public int MealId { get; set; }
}
// Vegetable.cs
public class Vegetable
{
public int Id { get; set; }
public string Name { get; set; }
public int MealId { get; set; }
}
// Drink.cs
public class Drink
{
public int Id { get; set; }
public string Name { get; set; }
}
是的,我知道在现实世界中,肉类和蔬菜与膳食之间的关系可能是多对多的,但不要在这里纠结。
// MealsContext.cs
public class MealsContext: DbContext
{
public MealsContext() : base("ConnectionString")
public DbSet<Meal> Meals{ get; set; }
public DbSet<Meat> Meats{ get; set; }
public DbSet<Vegetable> Vegetables { get; set; }
public DbSet<Drink> Drinks{ get; set; }
}
我的经验是使用 Model First 方法。EDMX 文件是在 POCO 之后构建的。
连接字符串中是映射到已解析 EDMX 资源 ( metadata=res://*/Models.MealsModels.csdl|res://*/Models.MealsModels.ssdl|res://*/Models.MealsModels.msl;) 的元数据部分。
我检查了 EDMX 文件的底层 XML,显示了概念模型和存储模型中存在的所有实体,并且所有实体都已完全映射。怎么回事?
故障排除
第一次尝试是完全摆脱存储和映射 EDMX 数据(SSDL和MSL部分)。开火,现在有两个例外:
检索
Meals投掷MSL, error 2062 No mapping specified for instance of the EntitySet and AssociationSet in the EntityContainer。检索
Drinks继续抛出The entity type Drinkis not part of the model for the current context。
引发的错误Meals是意料之中的,我对映射和存储模型进行了核对 - 检查_db表明Meals-> InternalSet->EntitySet属性是正确的,只是没有映射。
引发的错误Drinks是我卡住的地方。仔细检查_db我发现Drinks-> InternalSet->EntitySet抛出SystemInvalidOperation异常,指出实体不在模型上下文中。
以下是 EDMX 的 CSDL 在 XML 格式中的样子:
<edmx:ConceptualModels>
<Schema ...>
<EntityContainer Name="MealsContext" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Meals" EntityType="Models.Meal" />
<EntitySet Name="Meats" EntityType="Models.Meat" />
<EntitySet Name="Vegetables" EntityType="Models.Vegetable" />
<EntitySet Name="Drinks" EntityType="Models.Drink" />
<!-- AssociationSets here for the FKs -->
</EntityContainer>
<!-- All are present, but here's the culprit Drink -->
<EntityType Name="Drink">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Type="Int32" Name="Id" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Type="String" Name="Name" Nullable="false" MaxLength="200" FixedLength="false" Unicode="true" />
</EntityType>
<!-- Associations here -->
</Schema>
</edmx:ConceptualModels>
问题
如果DbContext具有所有DbSet属性并且正在使用一个连接字符串,其中包含一个模型的元数据,该模型的 CSDL 正确定义了实体类型Drink,为什么它不是上下文的一部分?
我能看到的唯一不同Drink的是它与任何其他实体都没有关系,也没有关联......