使用查找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。我會用這個上下文更新我的答案。 –