gpt4 book ai didi

c# - Entity Framework : An error occurred while updating the entries

转载 作者:行者123 更新时间:2023-12-05 01:45:34 32 4
gpt4 key购买 nike

我知道有很多关于它的问题,但我已经阅读了大约 20 个,但找不到适合我的答案。我有这个错误

"An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

Additional information: An error occurred while updating the entries. See the inner exception for details."

当我转到 InnerException 时,它说

"Invalid object name 'dbo.Samochodies'."

.我不知道这到底是什么,因为我的程序中没有任何“Samocodies”。无论如何,这就是代码:

CarsController.cs

public ActionResult Create([Bind(Include = "Id,Brand,Model,Price,Bought,Sold")] Samochody car)
{
if (ModelState.IsValid)
{
baza.Cars.Add(car);
baza.SaveChanges(); //error here
return RedirectToAction("Index");
}
return View(car);
}

萨摩奇类

public class Samochody
{
public int Id { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public decimal Price { get; set; }
public DateTime Bought { get; set; }
public DateTime Sold { get; set; }

public class CarDBCtxt : DbContext
{
public DbSet<Samochody> Cars { get; set; }
}

最佳答案

当您使用现有数据库时,如果您没有指定表名,那么 EF 将尝试按照惯例在您的数据库中查找名为 Samocodies 的表.一种解决方案是使用 Table 属性来指定真实的表名:

[Table("YourTableName")]
public class Samochody
{
//...
}

现在,异常(exception)可能是因为您更改了实体的名称。对于这种情况,EF 有一些初始化程序可以帮助您在每次更改模型时解决此类问题,在您的情况下它将是:

public class CarDBCtxt : DbContext
{
public DbSet<Samochody> Cars { get; set; }

public CarDBCtx(): base("CarDBCtxt")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CarDBCtxt>());
}
}

如果您想了解有关初始化器的更多信息,请查看此 link .

关于c# - Entity Framework : An error occurred while updating the entries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41172060/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com