繁体   English   中英

如何在ASP.NET MVC中设置一对多关系?

[英]How to setup one to many relationship in asp.net mvc?

我正在尝试在我的asp.net mvc应用程序中进行以下设置:

  1. 我正在使用AspNetUser处理用户。
  2. 一个用户可以拥有多辆汽车
  3. 一辆车可以进行多次维修

汽车模型

public class Car
{
    [Key]
    public int CarID { get; set; }

    [Required]
    public virtual ApplicationUser ApplicationUser { get; set; }

    public virtual ICollection<Maintenance> Maintenances { get; set; }

    [Required]
    public string Brand { get; set; }

    // a bunch of other string properties related to a car...
}

维修模式

public class Maintenance
{
    public int CarID { get; set; }

    [Key]
    public int MaintenanceID { get; set; }

    public int Mileage { get; set; }

    public DateTime EntryDate { get; set; }

    public DateTime ExitDate { get; set; }

    public decimal Cost { get; set; }

    public virtual Car Automobile { get; }
}

IdentityModels.cs

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<Car> Cars { get; set; }

    // ...
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Car>()
            .HasRequired(c => c.ApplicationUser)
            .WithMany(t => t.Cars)
            .Map(m => m.MapKey("OwnerID"));
    }

    public DbSet<Car> Cars { get; set; }
    public DbSet<Maintenance> Maintenances { get; set; }
}

我看了看表定义,它们似乎还可以(正确设置OwnerID外键),但是由于某些原因,当我尝试添加新车时,这不起作用:

public ActionResult Create(Car car)
{
    if (ModelState.IsValid)
    {
        db.Cars.Add(car);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(car);
}
  1. ModelState.IsValid始终为false
  2. car.ApplicationUser始终为null

我是asp.net mvc的新手,有人可以告诉我我在做什么错吗?

如果Car.ApplicationUser始终为null那么我建议您再次查看View,以查看是否有该属性的字段,我想是您没有。

因为您将Model指定为Controller Action的参数,所以:

public ActionResult Create(Car car)

然后MVC将尝试执行模型绑定,在此过程中,表单字段使用字段名称绑定到Car模型,以匹配模型属性。

提交给Controller动作的唯一内容是表单内的内容。

一种选择是将ApplicationUser字段作为表单中的隐藏字段包括在内,并且在将您发送到创建视图的Controller Action中,您将创建一个新的Car Model并在其中填充ApplicationUser,然后将其传递到View中。

@StephenMuecke遇到的另一个选择是专门为View创建一个模型,并在View中使用该ViewModel:

public class CarVM
{
    public ICollection<Maintenance> Maintenances { get; set; }

    [Required]
    public string Brand { get; set; }

    // a bunch of other string properties related to a car...
}

现在请注意,表单无需担心ApplicationUser字段即可将ModelState设置为Valid,在提交表单时,它将字段绑定到ViewModel中的属性,然后在该Post Action中,您将创建一个Car模型,并从发布的ViewModel中的数据中填充它,并抓住当前用户以填充ApplicationUser,然后从那里开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM