Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c# - select named field in ef core select statement which uses generics

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since your entities already inherit from the same base class which has the Id property, you can just constrain your generic type to that:

where TEntity : BaseEntity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...