EF代码 - 首先是多对多的附加数据

时间:2012-04-17 21:06:16

标签: sql-server entity-framework ef-code-first

我有这些表格:

CREATE TABLE [EDR_SECURITY].[Person](
    [ixPerson] [bigint] IDENTITY(1,1) NOT NULL,
    [sName] [nvarchar](200) NOT NULL,
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]



CREATE TABLE [EDR_SECURITY].[SecurityGroup](
    [ixSecurityGroup] [bigint] IDENTITY(1,1) NOT NULL,
    [sName] [nvarchar](200) NOT NULL,
    [sDescription] [nvarchar](400) NULL,
) ON [PRIMARY]


CREATE TABLE [EDR_SECURITY].[PersonSecurityGroupDefinition](
    [ixPerson] [bigint] NOT NULL,
    [ixSecurityGroup] [bigint] NOT NULL,
    [fPrivilege] [bigint] NOT NULL,
 CONSTRAINT [PK_PersonSecurityGroupDefinition] PRIMARY KEY CLUSTERED 
(
    [ixPerson] ASC,
    [ixSecurityGroup] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

如何在EF代码中创建PersonSecurity Group之间的关系?

感谢。

1 个答案:

答案 0 :(得分:4)

如果我完全理解原始SQL ......

编辑:并且根据您的具体情况,我认为这至少非常接近......

public class Person
{
    public int PersonID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<PersonSecurityGroupDefinition> 
        PersonSecurityGroups { get; set; }
}
public class SecurityGroup
{
    public int SecurityGroupID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<PersonSecurityGroupDefinition> 
        PersonSecurityGroups { get; set; }
}
public class PersonSecurityGroupDefinition
{
    public int PersonID { get; set; }
    public int SecurityGroupID { get; set; }
    public int Privilege { get; set; }
    // don't use virtual here as these are PK-s
    public Person Person { get; set; }
    public SecurityGroup SecurityGroup { get; set; }
}

...以及OnModelCreating(覆盖DbContext ...

modelBuilder.Entity<PersonSecurityGroupDefinition>()
    .HasKey(i => new { i.PersonID, i.SecurityGroupID });

modelBuilder.Entity<PersonSecurityGroupDefinition>()
    .HasRequired(i => i.Person)
    .WithMany(u => u.PersonSecurityGroups)
    .HasForeignKey(i => i.PersonID)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<PersonSecurityGroupDefinition>()
    .HasRequired(i => i.SecurityGroup)
    .WithMany(d => d.PersonSecurityGroups)
    .HasForeignKey(i => i.SecurityGroupID)
    .WillCascadeOnDelete(false);

......希望就是这样。