[英]Entity framework returns entity which doesn't exist in database
I got a very strange behavior with EF6.我对 EF6 有一个非常奇怪的行为。 I have an entity which insertion failed, but when i enumerate the entities, the first time after that, I retrieve the entity我有一个插入失败的实体,但是当我枚举实体时,之后的第一次,我检索了实体
static async Task Debug()
{
MyDbContext ctx = new MyDbContext();
Category category = new Category()
{
Name = "TEST INSERTION FAILED",
Reference = "KKK",
TranslationCategories = new List<TranslationCategory>()
{
new TranslationCategory()
{
//LangId = "FR", Force insertion failed
Name= "FR translation"
}
}
};
try
{
ctx.Categories.Add(category);
await ctx.SaveChangesAsync();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
// throw exception because "LangId" missing in Translation Category
}
MyDbContext ctx2 = new MyDbContext();
foreach(var o in ctx2.Categories.ToList())
{
Console.WriteLine(o.Name);
//output : "TEST INSERTION FAILED" + categories stored in DB
// Why category "TEST INSERTION FAILED" in ctx2.Categories ?
}
Console.WriteLine("****************");
foreach (var o in ctx2.Categories.ToList())
{
Console.WriteLine(o.Name);
// ouput : only categories stored in DB
}
}
Category entity generated by entity framework power tools实体框架强力工具生成的类别实体
public partial class Category
{
public Category()
{
this.Products = new List<Product>();
this.TranslationCategories = new List<TranslationCategory>();
}
public int CategoryId { get; set; }
public Nullable<int> ParentCategoryId { get; set; }
public string Reference { get; set; }
public System.DateTime CreationDate { get; set; }
public string Name { get; set; }
public Nullable<bool> Published { get; set; }
public string Artwork { get; set; }
public string TypeCode { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<TranslationCategory> TranslationCategories {get;set; }
}
I solved my problem.我解决了我的问题。 My entities and DBContext was generated using "entity framework power tools, reverse engineer code first".我的实体和 DBContext 是使用“实体框架强力工具,先逆向工程代码”生成的。 I have regenerated entities and dbcontext by adding Ado.net data entity model, Code First from Existing Database, and now the same code works.我通过添加 Ado.net 数据实体模型和现有数据库中的 Code First 重新生成了实体和 dbcontext,现在相同的代码可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.