加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何保存具有现有数据以及新数据的模型?

发布时间:2020-12-15 18:11:18 所属栏目:百科 来源:网络整理
导读:我目前拥有一个拥有现有数据和新数据的模型. 作为一个例子,这是我的模型 public class NameDetails { public int Id { get; set; } public string Name { get; set; } } 这是它目前拥有的模拟数据 ListNameDetails Names = new ListNameDetails{ new NameDet
我目前拥有一个拥有现有数据和新数据的模型.

作为一个例子,这是我的模型

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设置为身份(第一种模式的情况),并且您的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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读