c# - 使用 Entity Framework 等 ORM 更新数据库中保存的数据的方法是什么?

标签 c# database entity-framework

我对我的程序有一个疑问。我正在使用 Entity Framework 用 C# 编写控制台应用程序。该程序有两个一对多关系的表。第一个表称为“Car”,第二个表称为“DescriptionCar”。我假设数据库中有数据,并且我想使用特定汽车的 ID 添加描述。

目前我有类似的事情:

using (var context = new ContextClass())
{
    Car car = context.Cars.Single(a => a.CarId == id);
    DescriptionCar descriptionCar = new DescriptionCar();
}

一开始,我下载了特定汽车的数据,创建了一个新对象来添加描述,现在我不知道如何填写数据。

模型类:

public class Car
{
    public int CarId { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public string Fuel { get; set; }
    public int ProductionYear { get; set; }
    public string Color { get; set; }
    public int PowerEngine { get; set; }

    public virtual ICollection<DescriptionCar> DescriptionCars { get; set; }
}

public class DescriptionCar
{
    public int DescriptionCarId { get; set; }
    public string Description { get; set; }

    public Car Car { get; set; }
}

感谢您的帮助。

最佳答案

有几种不同的方法可以实现这一点。最简单的如下:

using (var context = new ContextClass())
{
    DescriptionCar descriptionCar = context.DescriptionCars.Single(a => a.CarId == id);
    descriptionCar.Description = "Your description";
    context.SaveChanges();
}

如果您分享您的实体类,我可以为您提供进一步帮助。

关于c# - 使用 Entity Framework 等 ORM 更新数据库中保存的数据的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52728836/

相关文章:

c# - 在 Web API 中处理无效的 JSONP 请求

php - mysql排序大于

php - 内容数据库 - 可以存储 HTML 吗?

linq - 如何使用 DbContext 更新对象?

c# - 使用 Xamarin iOS 获取可用的应用内存

javascript - 在 angularjs 中找不到 url

c# - 格式化具有最小小数位数的 double 类型

C# 查询命令 SQL 带引号

c# - 循环访问 IQueryable 与在 C# 中使用 Reader.Read() 循环访问 Datareader 相同吗

c# - Entity Framework 继承和持久化列