I am creating a WebAPI where the frontend will send back a list of entities. Some of which may already exist.
public void AddTags( List<Tag> tags) //input coming from frontend js
{
foreach(Tag tag in tags){
//check if tag exists in db
//if not, create one
}
}
I tried to use DbContext.Tags.Contains(tag) but I am not sure how to link tag with the existing tag entity in the database.
I am trying to do something similar to below:
Tag tag = new Tag();
tag.name = "foo";
tag.someProp1= "hello";
tag.someProp2= "world";
tag.someProp3= "123";
//tag.id = unique id is unknown, decided by db
//find an identical entity exists in db, link `tag` to it
//if no such entity exists, add to DbContext.Tags
I am looking for something like DbContext.Tags.Match(tag); Where given an entity, it’s looking for an identical one in db.
This may work for you. I assume that
Taghas some type of unique identifier (either an Id or Name property perhaps). So you can always do something like this:DBContext.Tags.Where(t => t.Id == tag.Id);Would that work for you?
UPDATE
Based on your comment above, I’m not sure what you are after. If you are only ‘adding’ then you don’t need to check if the Tags exist, correct?
If you know what you want to match against, you can do this yes?
DBContext.Tags.Where(t => t.name == tag.name && t.prop1 == tag.prop1).FirstOrDefault();