1

使用 Entity Framework 4 和代码,我将如何创建一个支持这种场景的模型:

在应用程序中,有用户,每个用户属于一个多个组,并且对于每个组,用户可以具有一个多个角色。

例子:

我希望能够说“给我 Lisa”,然后响应返回 lisa 的用户对象,以及她所属的组。对于每个组,都有一个列表属性,其中包含她对该特定组的所有角色

谁能帮我先用代码建模,任何帮助/代码示例,都会很棒!

/最好的问候文布拉德

4

1 回答 1

2

编辑:这是满足您要求的新模型。

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);
    }
}

如代码中所述,有一个小的缺点。您可以通过无法先由代码建模的附加 FK 来强制 DB 中的数据完整性来避免这种劣势。您可以使用自定义初始化程序来添加该 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])");
    }
}

只需将其添加到您的应用程序初始化中(仅用于调试 - 应用程序不应在发布时删除其数据库):

Database.SetInitializer(new CustomInitializer());
于 2011-03-21T06:47:11.273 回答