1

我有两个简单的模型类。

  1. Service
  2. Attendee

每项服务可由 1 人或多人参加。我希望CreateEdit视图基于所有与会者显示为复选框的服务,并且当任何已选择/未选择的它应该从数据库中的相应服务中添加或删除时。

我已经尝试构建它一个多星期了,但没有成功!任何帮助将不胜感激。

这些类的代码如下。

public class Service
{
    public int ServiceID { get; set; }
    public string Problem { get; set; }

    public virtual ICollection<Attendie> AttendedBy { get; set; }
}

public class Attendie
{
    public int AttendieID { get; set; }
    public string Name { get; set; }

    public virtual Service Service { get; set; }
}

public class ServiceAttendiesDBContext: DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
    public DbSet<Service> Services { get; set; }
    public DbSet<Attendie> Attendies { get; set; }
}

public class ServiceAttendiesInitializer : DropCreateDatabaseAlways<ServiceAttendiesDBContext>
{
    protected override void Seed(ServiceAttendiesDBContext context)
    {
        base.Seed(context);

        var attendies = new List<Attendie>
        {
            new Attendie{AttendieID=1,Name="Attendie1"},
            new Attendie{AttendieID=2,Name="Attendie2"},
            new Attendie{AttendieID=3,Name="Attendie3"}
        };

        attendies.ForEach(at => context.Attendies.Add(at));
        context.SaveChanges();

        var services = new List<Service>
        {
            new Service{ ServiceID=1,Problem="Problem1",AttendedBy=new List<Attendie>()},
            new Service{ ServiceID=2,Problem="Problem2",AttendedBy=new List<Attendie>()},
            new Service{ ServiceID=3,Problem="Problem3",AttendedBy=new List<Attendie>()}
        };

        services.ForEach(ser => context.Services.Add(ser));
        context.SaveChanges();

        services[0].AttendedBy.Add(attendies[0]);
        services[0].AttendedBy.Add(attendies[1]);
        services[1].AttendedBy.Add(attendies[2]);
        services[1].AttendedBy.Add(attendies[2]);
        services[2].AttendedBy.Add(attendies[1]);
        context.SaveChanges();

    }
4

0 回答 0