EF6的行为非常奇怪。我有一个插入失败的实体,但是当我枚举实体时,此后的第一时间,我检索了该实体
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
}
}
实体框架电动工具生成的类别实体
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; }
}
最佳答案
我解决了我的问题。我的实体和DBContext是使用“实体框架强大的工具,首先是反向工程师代码”生成的。
通过添加Ado.net数据实体模型,现有数据库中的Code First,我已经重新生成了实体和dbcontext,现在相同的代码可以工作了。
关于c# - Entity Framework 返回数据库中不存在的实体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32764941/