MVC如何将一个模型连接到另外两个模型

本文关键字:模型 两个 连接 MVC 一个 | 更新日期: 2023-09-27 18:28:15

我需要一些帮助来理解如何创建一个与其他两个模型链接的模型。

我有三种型号:

public class RequiredPower
{
  public int RequiredPowerID { get; set; }
  [Required(ErrorMessage = "This field cannot be empty!")]
  [MaxLength(25, ErrorMessage = "This name is too long. Max. 35 characters allowed!")]
  [Display(Name = "Name:")]
  public string Name { get; set; }
  public int Position { get; set; }
}
public class RequiredFuses
{
  public int RequiredFusesID { get; set; }
  [Required(ErrorMessage ="This field cannot be empty!")]
  [MaxLength(25,ErrorMessage ="This name is too long. Max. 25 characters allowed!")]
  [Display(Name="Fuse:")]
  public string Name { get; set; }
}
public class PowerConnector
{
  public int PowerConnectorID { get; set; }
  [Required(ErrorMessage = "This field is required!")]
  [Display(Name = "Name:")]
  [StringLength(45, ErrorMessage = "The name is too long, only 45 characters allowed!")]
  public string Name { get; set; }
  [StringLength(150, ErrorMessage = "The name is too long, only 150 characters allowed!")]
  [Display(Name = "Image file name:")]
  [DataType(DataType.MultilineText)]
  public string ImageName { get; set; }
}

这个想法是一个RequiredPower可以有多个PowerConnector和多个RequiredFuse。

在视图中,我有一个文本框,用于输入RequiredPower的名称、连接器的选择列表和保险丝的选择列表。选择列表是多个复选框列表,并提供一个由所选ID组成的字符串,如"1,2,3,"。

不知道如何在数据库中获取?我可以添加新的requiredPower,获取ID,然后用RequiredPowerID作为关系在其他两个表中分别创建记录,但使用EntityFramework不是更容易吗?

我在这里错过了什么?

MVC如何将一个模型连接到另外两个模型

在EF中,您可以使用虚拟集合定义一对多关系(您可以在此处看到更多信息):

public class RequiredPower
{
    public int RequiredPowerID { get; set; }
    [Required(ErrorMessage = "This field cannot be empty!")]
    [MaxLength(25, ErrorMessage = "This name is too long. Max. 35 characters allowed!")]
    [Display(Name = "Name:")]
    public string Name { get; set; }
    public int Position { get; set; }
    public virtual ICollection<PowerConnector> PowerConnectors { get; set; }
    public virtual ICollection<RequiredFuses> RequiredFuses { get; set; }
}

有了它,您可以将PowerConnectors/RequestedFuse添加到RequiredPower中,并立即保存:

var somePower = new RequiredPower() {
    Name = 'somePower'   
};
var oneConnector = new PowerConnector() {
    Name = 'oneConnector'   
};
somePower.PowerConnectors.add(oneConnector);
somePower.SaveChanges(); // << this will create somePower and oneConnector in your database