views:

38

answers:

1

I want to implement the below mentioned problem in Entity Framework.

I have 2 tables( below are their simplified versions)

items table

itemId,itemName

tags table

tagId,tagName
  • my logic is, an item can have more than one tag and a tag can have more than one item related to it, so I have added many to many relation (please correct me here, if I am wrong)

  • I have created model (edmx file) and database from it.

  • I have written code for adding data to my sample tables, and its working fine. Below is sample data

    itemId  itemName  ---items table
       1   |  fish
       2   |  cell phone
    
    
    tagId    tagName ------tags table
       1   |  eatable
       2   |  electronics
       3   |  non veg
    

I need to know how to write these 3 queries

  1. add relation between tag and item e.g. add tags "eatables", "nonveg" to item "fish"
  2. get all tags related to an item (eg: fish)
  3. get all tags not related to an item (eg: fish)
+1  A: 

If your association is in place with normal naming (an EDMX diagram in your question would help) ...

Q 1.

Tag tag = ...  // probably load from database or create if necessary
Item item = ...
item.Tags.Add(tag);

Q 2.

var tags = item.Tags;

Q 3.a All tags not related to ANY item

var unrelatedTags = context.Tags.Where(tag => tag.Items.Count() > 0);

Q 3.b All tags not related to a specific item

var unrelatedTags = context.Tags.Except(item.Tags);
Hightechrider
query 2 didnt work, in query 3 (ie for unrelated tags): iam looking for tags that are not related to a particular item. eg: in case "fish" i want it to return "electronics" as its the only tag out of all tags which is not related to fish
Praveen Prasad
Added 3b for a specific item. So what didn't work on Q2? How can Q1 work if Q2 doesn't for you? They use the same .Tags property.
Hightechrider
in q2 iam looking for all tags that are related to an item. in case of fish it should return eatable and non veg. i found the way : item.Tags is okie , but while writting query for item we have to incldue tag like:: var item= _context.items.include("tags").first(i=>i.name="fish"), now item.tags, is correct. iam still looking for third query.
Praveen Prasad

related questions