我有两个型号和一个dbcontext
:
public class User
{
public int UserId { get; set; }
public String UserName { get; set; }
public virtual ICollection<Conversation> Conversations { get; set; }
}
public class Conversation
{
public int ConversationId { get; set; }
public String Text { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
public class ChatContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Conversation> Conversations { get; set; }
}
我正在尝试添加会话实体,因此我需要从UserId
表中检索User
。到目前为止,我有:
var newtext = new Conversation()
{
Text = message, // message is sent from user
UserId = ChatContext.User.Where(u => u.UserName == name).Select(u => u.UserId)
};
我需要查询用户表以检索与该特定名称关联的userId
。我该怎么做到这一点?错误是:
ChatContext没有用户定义。
答案 0 :(得分:1)
首先:您必须将static
添加到Users
,如下所示:
public class ChatContext : DbContext
{
public static DbSet<User> Users { get; set; }
public DbSet<Conversation> Conversations { get; set; }
}
其次:您必须在查询中添加FirstOrDefault
方法,因为它会返回iQueryable
这样的内容:
var newtext = new Conversation()
{
Text = message, // message is sent from user
UserId = ChatContext.Users.FirstOrDefault(u => u.UserName == name).UserId
};
这应该有效。