实体框架,两个表之间的关系 [英] Entity Framework, relation between two tables
本文介绍了实体框架,两个表之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模型类是:
公共类用户
{
公共用户()
{
民调=新的List<&投票GT;();
}
公众诠释标识{搞定;组; }
公共字符串名字{搞定;组; }
公共字符串名字{搞定;组; } ICollection的<&投票GT;民意调查{搞定;组; }}公共类投票
{
公众诠释标识{搞定;组; }
公众诠释PositiveCount {搞定;组; }
公众诠释NegativeCount {搞定;组; }
公共字符串描述{搞定;组; }
公众用户用户{搞定;组; }}公共类PollsContext:的DbContext
{
公共DbSet<使用者>用户{搞定;组; }
公共DbSet<&投票GT;民意调查{搞定;组; }
}
EF创造了民意调查表的表user_id列。
在本次调查的创建视图,我要指定新的民意调查的用户ID属于过,但智能感知显示有到model.UserId进不去,有一个model.User.Id,这是不是让我创建一个投票现有的用户和相当创建了新的ID新用户,并不会创建任何关联。
< DIV CLASS =编辑标记>
@ Html.LabelFor(型号=> model.User.Id)
< / DIV>
< DIV CLASS =主编场>
@ Html.EditorFor(型号=> model.User.Id)
@ Html.ValidationMessageFor(型号=> model.User.Id)
< / DIV>
什么是为现有用户创建一个新的民意调查,然后以正确的方式?
解决方案
公共类投票
{
公众诠释标识{搞定;组; }
公众诠释PositiveCount {搞定;组; }
公众诠释NegativeCount {搞定;组; }
公共字符串描述{搞定;组; }
公众诠释用户ID {搞定;组; }
公众用户用户{搞定;组; }
}
My model classes are:
public class User
{
public User()
{
Polls = new List<Poll>();
}
public int Id { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
ICollection<Poll> Polls { get; set; }
}
public class Poll
{
public int Id { get; set; }
public int PositiveCount { get; set; }
public int NegativeCount { get; set; }
public String Description { get; set; }
public User User { get; set; }
}
public class PollsContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Poll> Polls { get; set; }
}
EF created a table User_Id column for Polls table. In the Create view of the Poll, I want to specify the UserId for new poll belongs too, but intellisense shows there is no access to model.UserId, there is a model.User.Id, which is not allowing me create a Poll for existing user and rather creates new User with new Id and no association is created.
<div class="editor-label">
@Html.LabelFor(model => model.User.Id)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.User.Id)
@Html.ValidationMessageFor(model => model.User.Id)
</div>
What is the right way of creating a new Poll for an existing User then ?
解决方案
public class Poll
{
public int Id { get; set; }
public int PositiveCount { get; set; }
public int NegativeCount { get; set; }
public String Description { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
这篇关于实体框架,两个表之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文