Home > Software design >  How to add the current row from a list to a DbSet
How to add the current row from a list to a DbSet

Time:06-24

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
    {

    }
});

CodePudding user response:

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();

CodePudding user response:

in EFcore u have to know Your entity then you need this code:

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