2017-03-03 56 views
0

为一连串餐厅建立管理门户。我在EF Code First中使用ASP.NET MVC。ASP.NET MVC客户门户用户连接表

我希望每个用户登录后只能看到连接到它们的rescources。我想在ApplicationUser和Restaurant-class(模型)之间放置一个联结表(多对多),因为每个用户都可以在许多餐馆工作/工作,并且每个餐厅都可以有很多所有者/工作者。

您如何在EF代码中做到这一点?同样的方式,我做了餐厅 - > Menue?你是否需要为Applicationuser构建一个新的DBContext才能工作?

enter image description here

public class Restaurant 
{ 

    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Adress { get; set; } 
    public string PhoneNumber { get; set; } 
    public DateTime StartDate { get; set; } 

    //Connections 
    public virtual ICollection<Menue> Menues { get; set; } 
} 

public class Menue 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public bool IsActive { get; set; } 
    public DateTime ModifyDate { get; set; } 

    //FK For RestaurantConnection 
    public int RestaurantId { get; set; } 
} 

回答

2

对于多对多配置做这样

Student类应该有一个课程集合导航属性,当然应该有学生集合导航属性

public class Student 
{ 
    public Student() 
    { 
     this.Courses = new HashSet<Course>(); 
    } 

    public int StudentId { get; set; } 
    [Required] 
    public string StudentName { get; set; } 

    public virtual ICollection<Course> Courses { get; set; } 
} 

public class Course 
{ 
    public Course() 
    { 
     this.Students = new HashSet<Student>(); 
    } 

    public int CourseId { get; set; } 
    public string CourseName { get; set; } 

    public virtual ICollection<Student> Students { get; set; } 
} 

y我们的DbContext添加该配置

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
modelBuilder.Entity<Student>() 
      .HasMany<Course>(s => s.Courses) 
      .WithMany(c => c.Students) 
      .Map(cs => 
        { 
         cs.MapLeftKey("StudentRefId"); 
         cs.MapRightKey("CourseRefId"); 
         cs.ToTable("StudentCourse"); 
        }); 

} 

欲了解更多信息,请阅读这篇文章Configure Many-to-Many relationship

+0

非常感谢答案,伟大工程! –