Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Intersecting elements in Entity Framework entities with Linq

I have an Entity Framework entity in my ASP.NET Core 3.1 MVC project called Tag, which is a simple model:

public class Tag
{
    public string TagName { get; set; }
    public string TagNameNormalized { get; set; }
    public DateTime CreatedAt {get; set; }
    public string CreatedBy {get; set; }
}

A user can add tags from the website, and these tags are stored in a ICollection<Tag>. But I want to store only new tags, and not duplicates.

At some point, I need to evaluate the ICollection that holds the newly added tags against the ones already stored in the database (_context). I just want unique names (the TagName property), the other properties can be the same.

Right now, I'm doing this:

ICollection<Tag> duplicateTags = _context.Tags.ToList().Intersect(tagsToCheck).ToList();

but this is probably not doing what I want, because it will evaluate all of the model's properties.

What kind of Linq query should I use, where I evaluate just the TagName property, but still select the whole entity?

Any help and suggestions are appreciated!

question from:https://stackoverflow.com/questions/65645082/intersecting-elements-in-entity-framework-entities-with-linq

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

1 Answer

0 votes
by (71.8m points)

You can use linq Join

ICollection<Tag> duplicateTags = _context.Tags.Join(
                                  tagsToCheck,
                                  t => t.TagName, c => c.TagName, 
                                  (t,c) => t).ToList()

The above will give the duplicate tag objects.

Another way

var tagsNameToCheck = tagsToCheck.Select(t => t.TagName);
ICollection<Tag> duplicateTags = _context.Tags.Where(
                                  t => tagsNameToCheck.Contains(t.TagName))
                                  .ToList();

Point to notice that _context.Tags.ToList() would bring all tags from database into memory which can be a performance issue in your case if there are numerous tags. Would suggest to go for 2nd solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...