我对MVC有同样的问题,我发现的最好的解决方案是在我的模型上使用ForeignKey数据注释,这样我可以只插入相关对象的ID并在稍后检索对象。这里有一个例子:
public class Product {
public int ProductId { get; set; }
public string Name { get; set; }
// Add this field so I can add the entity to the database using
// category id only, no need to instantiate the object
public int CategoryId { get; set; }
// Map this reference to the field above using the ForeignKey annotation
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
public class Category {
public int CategoryId { get; set; }
public string Name { get; set; }
}
现在,它一直年龄,因为我最后一次使用的WebForms,所以我真的不知道该怎么类别列表绑定到DropDownList的,也许是这样的:
<asp:DropDownList ID="CategoryId" SelectMethod="GetCategories" runat="server" />
也许当你的产品返回到你的创建或更新方法时,它会随着CategoryId属性的正确归属而出现,然后你所要做的就是保存EF的上下文。祝你好运。