I have the method below which will insert new records into my database
public static async Task SaveDataToEntitySetAsync<TEntity>(DbContext context,List<TEntity> list)
where TEntity : class
{
if(list.Any() == false)
return;
var dbSet = context.Set<TEntity>();
var existingData = await dbSet.Select(x=>x.Id).ToListAsync();
list.RemoveAll(x => existingData.Contains(x.Id));
await dbSet.AddRangeAsync(list);
}
The logic above is what I am trying to do if I wasnt using generics
How can I convert this into a syntax which will work for generics? This syntax wont work in a generic context as .Id is not valid
I am using EF Core so when a record is added to a table, EF core is automatically adding records into the associated foreign key tables
The problem with this approach is that I call this method for each table in my context.
So lets say a customer in the UK is added. This is fine, the customer gets added, and the Country UK is added (assuming its not already there)
I also have an extract of all the countries which I save to the database. Obviously this will now break because UK has already been saved
Therefore I am trying to remove any items from my countries list which are already in the database
All of my entities come off of a BaseEntity (which is where Id is defined) but Im not sure how to make use of that fact
Paul
question from:
https://stackoverflow.com/questions/65876226/select-named-field-in-ef-core-select-statement-which-uses-generics 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…