gpt4 book ai didi

c# - 如何保存具有现有数据和新数据的模型?

转载 作者:可可西里 更新时间:2023-11-01 09:14:22 24 4
gpt4 key购买 nike

我目前有一个包含现有数据和新数据的模型。

举个例子,这是我的模型

 public class NameDetails
{
public int Id { get; set; }
public string Name { get; set; }

}

这是它当前拥有的模拟数据

  List<NameDetails> Names = new List<NameDetails>{

new NameDetails{Id = 1, Name = "Name 1"},
new NameDetails{Id = 2 , Name = "Name 2"},
};

现在假设我需要将它保存到数据库中。我已经在表中有 id = 1,所以这应该是一个更新,因为 id = 2 应该是一个添加...我该怎么做?

以前,当我使用存储库编写保存时,我会进行添加或编辑像这样添加,

 context.NameDetails.Add(NameDetails); 
context.SaveChanges();

或者像这样编辑,

var recordToUpdate = context.NameDetails.FirstOrDefault(x => x.Id== 1);
recordToUpdate.Name = "New name";
context.SaveChanges();

那么这是否意味着我必须遍历我的列表并计算出什么是新的,什么不是.. 或者有其他方法吗?

最佳答案

您可以使用一些适用于 Entity Framework 的约定。

例如,如果您在数据库中使用 IDENTITY(1,1)(因此它会自动为您插入的行生成 ID),您的实体属性应该使用 StoreGeneratedPattern设置为 Identity(模型优先方法的情况),并且您的 Id 属性具有 0 值意味着 它尚未添加到数据库

然后您可以轻松地决定要添加什么以及要更新什么。这是一些伪(未经测试的)代码:

foreach (var entity in entities)
{
if (entity.Id == 0)
{
// Adds to the context for a DB insert
context.Entities.Add(entity);
}
else
{
// Updates existing entity (property by property in this example, you could update
// all properties in a single shot if you want)
var dbEntity = context.Entities.Single(z => z.Id == entity.Id);
dbEntity.Prop1 = entity.Prop1;
// etc...
}
}

context.SaveChanges();

关于c# - 如何保存具有现有数据和新数据的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17834068/

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