Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4085098
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T18:31:39+00:00 2026-05-20T18:31:39+00:00

Using Entity Framework 4 and code first how would I create a model that

  • 0

Using Entity Framework 4 and code first how would I create a model that supports this scenario:

In an application, there are users, each user belongs to one or more groups and for each group the user can have one or more roles.

Example:

I would like to be able to say, “give me Lisa”, and the response returns a user object for lisa, with the groups she belongs to. For each group there is a list property with all the roles she has for that particular group

Can anyone help me model this using code first, any help/code samples, would be great!

/Best regards Vinblad

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T18:31:40+00:00Added an answer on May 20, 2026 at 6:31 pm

    Edit: Here is new model for your requirement.

    public class User
    {
        public virtual int Id { get; set; }
        public virtual ICollection<UserPermission> Permissions { get; set; }
    }
    
    // Permission is extended junction table to model M:N between 
    // User and Group but in addition it contains relation to Roles.
    // The ony disadvantage is that this model doesn't control that
    // role in the collection is also the role related to group. You
    // must either enforce it in application logic or create some additional
    // database construct to check it.
    public class UserPermission
    {
        public virtual int UserId {  get; set; }
        public virtual int GroupId { get; set; }
    
        public virtual Group Group { get; set; }
        public virtual ICollection<Role> Roles { get; set; }
    }
    
    public class Group
    {
        public virtual int Id { get; set; }
        public virtual ICollection<UserPermission> UserPermissions { get; set; }
        public virtual ICollection<Role> Roles { get; set; }
    }
    
    
    public class Role
    {
        public virtual int Id { get; set; }
        public virtual ICollection<Group> Groups { get; set; }
        public virtual ICollection<UserPermission> UserPermissions { get; set; }
    }
    
    public class Context : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Group> Groups { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<UserPermission> UserPermissions { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            // Permission has composite key
            modelBuilder.Entity<UserPermission>()
                .HasKey(p => new {p.UserId, p.GroupId});
    
            // Permission doesn't have navigation property to user
            modelBuilder.Entity<User>()
                .HasMany(u => u.Permissions)
                .WithRequired()
                .HasForeignKey(p => p.UserId);
    
            modelBuilder.Entity<Group>()
                .HasMany(g => g.UserPermissions)
                .WithRequired(p => p.Group)
                .HasForeignKey(p => p.GroupId);
        }
    }
    

    As described in code there is small disadvantage. You can avoid the disadvantage by enforcing data integrity in DB by additional FK which can’t be modeled by code first. You can use custom initializer to add that FK:

    public class CustomInitializer : DropCreateDatabaseIfModelChanges<Context>
    {
        protected override void Seed(Context context)
        {
            context.Database.ExecuteSqlCommand(
                @"ALTER TABLE [dbo].[RoleUserPermissions]  
                 WITH CHECK ADD CONSTRAINT [FK_RoleUserPermissions_RoleGroups] 
                 FOREIGN KEY([Role_Id], [UserPermission_GroupId])
                 REFERENCES [dbo].[RoleGroups] ([Role_Id], [Group_Id])");
        }
    }
    

    Just add this to your application initialization (only for debug – application should not be able to drop its database in release):

    Database.SetInitializer(new CustomInitializer());
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When using Entity Framework Code First 4.3.1 it is possible to create relationships with
I'm using Entity Framework 4.3 Code First with a custom database initializer like this:
I am creating a new database model using Entity Framework 4.3 Code-FIrst; using Fluent
Using Entity Framework 4.1 code first and POCO entities in MVC3; I would like
Background We have a WinForms application with Entity Framework 4.2 code-first / FluentAPI using
I have an ASP.NET MVC 3 application using an Entity Framework (4.3.1) Code First
In my application I'm using Entity Framework 4.0 Model First. I have several tables
I'm using Entity Framework Code First. The class i'm trying to create contains two
Let me explain the title. I'm using Entity Framework Code First in an application
I'm using Entity Framework 4.1 Code First and I have a table that has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.