简体   繁体   中英

How to add the current row from a list to a DbSet

I'm trying to iterate in each row from a list, if the current row from the list has no record yet in the database hence add the current row, otherwise continue to next iteration. how can i add the current row in the list to my DbSet.

list.ForEach(x =>
{
    objInsuredList = (from obj in _db.dbLifeData
    where (obj.identifier == x.identifier) && (obj.plan == x.plan) && (obj.policyno == x.policyno)
    select obj).ToList(); //get all existing record
    
    var query = _db.dbLifeData.FirstOrDefault(y => y.identifier == x.identifier 
      && y.policyno == x.policyno && y.plan == x.plan); //check current in list if it exists

    if(query != null)
    {
     query.status = x.status;
     _db.Entry(query).State = EntityState.Modified;
     _db.SaveChanges();

    }
    else //current row has no record yet in the dbLifeData database
    {

    }
});

In EF Core you have to know your entity then you need this code:

DbSet<Object>().Add(query);
efDataContext.SaveChanges();

I would suggest to improve your code, otherwise you will have big performance issues.

Copy FilterByItems helper extension to your code base

// get existing items in one DB roundtrip
var existing = _db.dbLifeData
    .FilterByItems(list, (obj, x) => (obj.identifier == x.identifier) && (obj.plan == x.plan) && (obj.policyno == x.policyno), true)
    .AsEnumerable()
    .ToDictionary(x => (x.identifier, x.plan, x.policyno));

foreach(var x in list)
{
    var key = (x.identifier, x.plan, x.policyno);
    if (existing.TryGetValue(key, out var found))
    {
        // EF Core smart enough to detect changes in properties
        found.status = status;
    }
    else
    {
        var newRecord = new dbLifeData
        {
            status = x.status,
            identifier = x.identifier, 
            plan = x.plan,
            policyno = x.policyno
        };

        _db.dbLifeData.Add(newRecord);
    }
}

// save everything in one batch
_db.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM