我需要一些帮助来了解如何创建与其他两个模型链接的模型。
我有三种模式:
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和多个RequiredFuses。
在视图上我有一个文本框,用于输入RequiredPower的名称,连接器选择列表和保险丝选择列表。 选择列表是多个复选框列表,并提供一系列选择的ID,如" 1,2,3,"。
没有如何在数据库中获得它? 我可以添加新的requiredPower,获取ID,然后在RequiredPowerID作为关系的情况下在其他两个表中单独创建记录,但是使用EntityFramework会不会更容易?
我在这里缺少什么?
答案 0 :(得分:2)
在EF中,您可以使用虚拟集合定义一对多关系(您可以看到more here):
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 / RequiredFuses添加到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