简体   繁体   English

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

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

I'm trying to have this setup in my asp.net mvc app: 我正在尝试在我的asp.net mvc应用程序中进行以下设置:

  1. I'm using AspNetUser to handle users. 我正在使用AspNetUser处理用户。
  2. One user can have many cars 一个用户可以拥有多辆汽车
  3. One car can have many repairs 一辆车可以进行多次维修

Car model 汽车模型

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

Maintenance model 维修模式

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

I took a look at table definitions, they seems to be OK ( OwnerID foreign key is correctly setup), but for some reason this doesn't work when I try to add a new car: 我看了看表定义,它们似乎还可以(正确设置OwnerID外键),但是由于某些原因,当我尝试添加新车时,这不起作用:

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

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

I'm new to asp.net mvc, can someone please tell me what I'm doing wrong here? 我是asp.net mvc的新手,有人可以告诉我我在做什么错吗?

If the Car.ApplicationUser is always null then I would suggest you look at your View again to see if you have a field for that property, my guess is you don't. 如果Car.ApplicationUser始终为null那么我建议您再次查看View,以查看是否有该属性的字段,我想是您没有。

Because you specify the Model as the parameter for the Controller Action: 因为您将Model指定为Controller Action的参数,所以:

public ActionResult Create(Car car)

then MVC will attempt to perform Model Binding and in this process the form fields are bound to the Car model using the names of the fields to match up to the model properties. 然后MVC将尝试执行模型绑定,在此过程中,表单字段使用字段名称绑定到Car模型,以匹配模型属性。

The only things submitted to the Controller action are those that are within the form. 提交给Controller动作的唯一内容是表单内的内容。

One option is to include the ApplicationUser field as a hidden field in the form, and within the Controller Action that sends you to the Create View you would create a new Car Model and populate the ApplicationUser there and then pass that into the View. 一种选择是将ApplicationUser字段作为表单中的隐藏字段包括在内,并且在将您发送到创建视图的Controller Action中,您将创建一个新的Car Model并在其中填充ApplicationUser,然后将其传递到View中。

Another option that @StephenMuecke was getting at was creating a model specifically for the View, and use that ViewModel in the 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...
}

and notice now that the form wouldn't need to worry about the ApplicationUser field in order to get the ModelState to Valid, when the form is submitted it would bind the fields to the properties in the ViewModel, and then in that Post Action you would create a Car model and populate it from the data in the ViewModel that was posted, and grab the current user to populate ApplicationUser, and go from there. 现在请注意,表单无需担心ApplicationUser字段即可将ModelState设置为Valid,在提交表单时,它将字段绑定到ViewModel中的属性,然后在该Post Action中,您将创建一个Car模型,并从发布的ViewModel中的数据中填充它,并抓住当前用户以填充ApplicationUser,然后从那里开始。

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

相关问题 如何在ASP.NET MVC中映射许多一对多关系? - How to Map many one-to-many relationship in ASP.NET MVC? 处理MVC 4 ASP.NET中的“多对一”关系 - Handling a 'Many to One' Relationship in MVC 4 ASP.NET asp.net mvc 4一对多关系(文章-标签) - asp.net mvc 4 one to many relationship (article - tags) 如何使用ASP.NET MVC 5在EF中实现多对多关系 - How to implement many to many relationship in EF with ASP.NET MVC 5 如何在ASP.NET MVC 5中创建HtmlDropdownListfor而不使用一对多关系中的模型视图 - How to create HtmlDropdownListfor in asp.net mvc 5 without use of modelviews in one to many relationship ASP.Net MVC 如何在ApplicationUser和我自己的类之间建立一对多的关系? - ASP.Net MVC How to create a one-to-many relationship between the ApplicationUser and my own class? 如何在代码优先的ASP.NET MVC 5应用程序中以一对多关系正确设置外键约束 - How to correctly set foreign key constraint in one to many relationship in code first ASP.NET MVC 5 application ASP.NET MVC3和实体框架 - 一个视图中的一对多关系 - ASP.NET MVC3 and Entity Framework- one-to-many relationship in one view ASP.net MVC实体框架更新多对多关系 - ASP.net MVC Entity framework update Many to Many relationship 使用EF 5和ASP.NET MVC 4为多对多关系添加值 - Add value to Many to Many relationship with EF 5 & ASP.NET MVC 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM