0

I'm pretty new to the Entity framework and I'm modelling this simple structure:

enter image description here

With this model what I have is a Users class with a property UsersGroups (a collection of UserGroups objects).

I would like to have a Users class with a property like Groups with type Tuple or something like this (a new PriorizedGroup class, etc) that is much more related with the bussines.

Is this possible with the Entity framework?

Thanks in advance.

EDIT: If I were modeling the bussines objects I would create a User class with a Groups property that contained all the groups the user pertains with an extra property to store its priority (with a tuple, with an inherited class, as you wish). The thing is that I feel that the objects created by the Entity framework resemble the SQL structure, not the business structure.

Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207
  • What would be difference between a new `PrioritizedGroup` and `UserGroups` you already have? – Ladislav Mrnka Aug 18 '11 at 10:34
  • A prioritized group will be just a group with an extra property Priority. I think that has no sense to have a UsersGroups property at the Users object because the UserId of UsersGroups will be the User Id so you just need a property at the Users with all the Groups the user has and its priority. – Ignacio Soler Garcia Aug 18 '11 at 10:40

1 Answers1

1

Not directly. EF can map the relation only in the way you see it at the moment but you can add your custom behavior to your partial part of the entity. The simple way is something like

public partial class Users
{
    public IEnumerable<PrioritizedGroup> Groups 
    { 
        get
        {
            return UserGroups.Select(ug => new PrioritizedGroup
                                                   {
                                                        Priority = ug.Priority,
                                                        Id = ug.Group.Id,
                                                        Name = ug.Group.Name,
                                                        Description = ug.Group.Description 
                                                   })
                             .OrderBy(g => g.Priority);
        }  
    }
}

To make this happen directly in EF you need some advanced mapping technique which will require you to modify EDMX source code directly (either DefiningQuery or QueryView) and it will make the entity read only (you will need stored procedures for modification).

To make the collection exposed on Users updatable you would probably need to use ObservableCollection and transfer all modifications triggered by ObservableCollection back to original UserGroups collection. Once you have something like that implemented you can hide original collection.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670