1

I've just started a project using LINQ to SQL, and I've clashed against the many-to-many problem. I've found a lot of possible solution, and I've choose this one.

Anyway, the affected db tables look like this:

Customer (idcustomer,other stuff..)
Customer_Role(idcustomer, idrole, other_attribute_I_want_to_keep )
Role(idrole, other stuff)

Now on, how can I handle the "other_attribute_I_want_to_keep? It would be great to have it like this:

Customer c.Role.other_attribute_I_want_to_keep, but I cannot spot a possible solution.

Thanks

1 Answer 1

2

You can't use many-to-many for this. Rather you'll need to make CustomerRole a first class object that BelongsTo both a Customer and a Role. Customer and Role in turn should be each declare a HasOne attribute for CustomerRole. Then you can do:

c.CustomerRole.Role
c.CustomerRole.OtherAttribute

You can make a shortcut Role attribute on Customer defined as:

[NotMapped]
public Role Role { 
    get { return CustomerRole == null ? (Role)null : CustomerRole.Role; } 
    set { if (CustomerRole == null)
            CustomerRole = new CustomerRole(){ Role = value };
          else
            CustomerRole.Role = value;
    }
}

but be aware that you may run into trouble using this shortcut when building a complex query.

9
  • That would be a solution if no other is possible, otherwise, is it possible to make "CustomerRole" a Dictionary<idrole,customerRole> instead of a IEnumerable<CustomerRole>?
    – ArtoAle
    Aug 31, 2012 at 15:50
  • I'm not sure how you intend to such a Dictionary, can you elaborate?
    – PinnyM
    Aug 31, 2012 at 15:54
  • sorry, but how can a CustomerRole attribute could possibly be ok? I mean, it's a collection, so it would be CustomerRoleS, and I cannot understand how the shortcut attribute you have defined coud work
    – ArtoAle
    Aug 31, 2012 at 15:57
  • sorry, of course: suppose I have a "Customer" entity, with LINQ to SQL I have direct access to the "CustomerRoles" collection. It would be nice if it can be a Dictionary (with idrole as key) instead of a IEnumerable flat collection
    – ArtoAle
    Aug 31, 2012 at 16:01
  • you can easily make a dictionary using context.CustomerRoles.ToDictionary(cr => cr.IdRole)
    – PinnyM
    Aug 31, 2012 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.