【问题标题】:ASP.NET MVC customer portal User Junction TableASP.NET MVC 客户门户用户连接表
【发布时间】:2017-03-03 18:42:26
【问题描述】:

我正在为连锁餐厅构建一个管理门户。我正在使用 ASP.NET MVC 和 EF Code First。

我希望每个用户在登录后只能看到与其连接的资源。我想在 ApplicationUser 和 Restaurant-class(model) 之间放置一个联结表(多对多),因为每个用户可以在许多餐馆拥有/工作,并且每个餐馆可以有许多所有者/工人。

您如何首先在 EF 代码中执行此操作?就像我做餐厅一样——>菜单?您是否需要为 Applicationuser 构建一个新的 DBContext 才能使其工作?

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

【问题讨论】:

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


    【解决方案1】:

    对于多对多的配置,这样做

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

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

    在你的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      相关资源
      最近更新 更多