>我有两个模型和一个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; }
}
我正在尝试添加一个对话实体,所以我需要从表中检索User
UserId
。到目前为止,我有:
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没有用户的定义。
首先:您必须像这样将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
};
这应该有效。