ASP.net有很多关系

时间:2016-10-27 20:05:15

标签: c# asp.net asp.net-mvc

我对ASP.NET MVC应用程序中的多对多关系有疑问。我用以下代码创建了数据库:

CREATE TABLE [dbo].[Address] (
[AddressId] INT          IDENTITY (1, 1) NOT NULL,
[Country]   VARCHAR (50) NOT NULL,
[City]      VARCHAR (50) NOT NULL,
[Street]    VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([AddressId] ASC)
);


CREATE TABLE [dbo].[Employee] (
[EmployeeId] INT          IDENTITY (1, 1) NOT NULL,
[Name]       VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([EmployeeId] ASC)
);

CREATE TABLE [dbo].[Employee_Address] (
[Employee_EmployeeId] INT NOT NULL,
[Address_AddressId]   INT NOT NULL,
PRIMARY KEY CLUSTERED ([Employee_EmployeeId] ASC, [Address_AddressId] ASC),
CONSTRAINT [FK_Employee_EmployeeId] FOREIGN KEY ([Employee_EmployeeId]) REFERENCES [dbo].[Employee] ([EmployeeId]),
CONSTRAINT [FK_Address_AddressId] FOREIGN KEY ([Address_AddressId]) REFERENCES [dbo].[Address] ([AddressId])
);

两个表(地址和员工),带有链接表(employee_address)。 我有以下课程:

public partial class Employee
{
    public Employee()
    {
        this.Addresses = new HashSet<Address>();
    }

    public int EmployeeId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public partial class Address
{
    public Address()
    {
        this.Employees = new HashSet<Employee>();
    }

    public int AddressId { get; set; }
    public string Country { get; set; }
    public string City { get; set; }
    public string Street { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

public partial class Database1Entities : DbContext
{
    public Database1Entities()
        : base("name=Database1Entities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
        .HasMany<Address>(s => s.Addresses)
        .WithMany(c => c.Employees)
        .Map(cs =>
        {
            cs.MapLeftKey("EmployeeId");
            cs.MapRightKey("AddressId");
            cs.ToTable("Employee_Address");
        });
    }

    public virtual DbSet<Address> Addresses { get; set; }
    public virtual DbSet<Employee> Employees { get; set; }
}

现在我希望在创建员工时,我可以使用复选框或下拉列表为员工分配一个或多个地址。我怎么能做到这一点?

我已经尝试了这个答案 topic

但我无法弄清楚我需要从项目的答案中添加什么。

提前感谢您的帮助。

0 个答案:

没有答案