如何处理控制器中的一对多关系 [英] How to handle one to many relationship in controller
问题描述
你好程序员,请跟我一起讨论我的问题,因为我正在学习ASP.NET MVC。
我有两个类:鞋子和颜色。
鞋子有很多颜色。
鞋子实体
Hello Programmers, Please bear with me with the way i am going to ask my question because i am learning ASP.NET MVC on my own.
I have two class : Shoe and color.
A shoe will have many colors.
Shoe Entity
public string shoeId{get;set;}
public string BrandName {get;set;}
public string Size {get;set:}
public virtual string ColorId {get;set:}
[ForeignKey("ColorId")]
public virtual ICollection(Color) Colors {get;set;}
颜色实体
Color Entity
public string ColorId {get;set;}
public string ColorName {get;set;}
public string PictureSamnple {get;set;}
public virtual string shoeId {get;set:}
如果我在控制器中构建两个实体,我将遇到问题尝试创建新鞋时使用create方法。
如果我使用@ Html.HiddenFor(e => e.ColorId)
@ Html.HiddenFor(e => e.shoeId)在SHoe的Create视图中,我在尝试提交时会出错。
我想要的是,当你重新创建鞋子时,你也会在提交之前创建一种颜色,但这有点困难。请帮助我。
If i scaffold both entitys in the controller, i will have problem with the create method when trying to Create a new Shoe.
If i use @Html.HiddenFor(e => e.ColorId)
@Html.HiddenFor(e => e.shoeId) in the Create view of SHoe, i will get an error when trying to submit.
what i am trying to achive is that when you re creating the shoe, you will also create a color before submitting it but it is kind of difficult. please, help me.
推荐答案
使用流畅的api以有效的方式映射实体。例如,您可以按照以下方式映射鞋子和颜色之间的一对多关系 -
Use fluent api for mapping entities in efficient way. For example you can map the one to many relationship between shoe and colors in following way -
public class ShoeMapper : EntityTypeConfiguration<Shoe>
{
public ShoeMapper()
{
HasMany(x => x.Colors).WithRequired().HasForeignKey(x => x.ShoeId);
}
}
除此之外你应该创建一个单独的表
Apart from this you should create a separate table
tbl_Colors
[int_Id, varchar_Name]
然后是联结表
tbl_Shoes_Colors
[fk_Shoes_Id, fk_Colors_Id, varchar_SampleImage]
按照规范化建议映射关系。
to map relation as per normalization recommendation.
这篇关于如何处理控制器中的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!