0

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!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CMorgan
  • 645
  • 2
  • 11
  • 33

2 Answers2

1

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.

user1672994
  • 10,509
  • 1
  • 19
  • 32
0

Morgan,

You can use Distinct(). For example:

ICollection<Tag> duplicateTags = _context.Select(t => t.TagName).Distinct().ToList()

Does this answer your question?

Jim Simson
  • 2,774
  • 3
  • 22
  • 30