使用查找dbSet记录我有一个用户表:查找无主键
Users:
+ID
+Username
+...
我想用myDBContext.Users.Find(Username)
到鳍用户。 在我目前的情况下,我不能使用他的ID。
我必须使用完整的LINQ查询吗?例如
var user = from users in myDBContext.Users.Find(Username)
where users.Username == username
select users
我也试图定义的用户名在我的EDMX一个主键,但是,导致以下错误:
Properties referred by the Principal Role User must be exactly identical to the key of the EntityType CamelotShiftManagementModel.User referred to by the Principal Role in the relationship constraint for Relationship CamelotShiftManagementModel.AssociationUserFK1. Make sure all the key properties are specified in the Principal Role. C:\Code\CamelotShiftManagement\CamelotShiftManagement\Models\CamelotDB.edmx 278 11 CamelotShiftManagement
更好! .. 谢谢。 – Mortalus
改用'FirstOrDefault'会不会更好?我对SingleOrDefault方法的理解是,它将浏览* whole *表以确保只有一条记录与条件匹配。这可能不是OP想要的。 – Crono
@Crono是的,如果我们考虑它与SingleOrDefault相比的性能,那么你是正确的FirstOrDefault。但在这里,我认为取决于预期的结果,我们应该在这两种方法之间进行选择。如果你只想要单个结果,并且如果有多个序列相同,那么你需要一个异常,然后使用SinleOrDefault,否则使用FirstOrDefault。我会用这个上下文更新我的答案。 –