我有一個郵政實體Id和用戶屬性。 用戶是IdentityUser。 我的實體沒有UserId屬性,因爲我不需要它。如何檢查EF核心中的主鍵和外鍵情況?
如何以最佳方式檢查該帖子是否屬於當前用戶? 我想過這個
var currentUser = await userManager.GetUserAsync(httpAccessor.HttpContext.User);
if (!await context.Posts.FromSql(
@"SELECT TOP 1 UserId
FROM Posts
WHERE Id = {0}", postId).Any(Id => Id == currentUser.Id))
throw new InvalidOperationException("Post does not belong to current user.");
或本
if (!await context.Posts.AnyAsync(p => p.Id == post.Id && p.User.Id == currentUser.Id))
throw new InvalidOperationException("Post does not belong to current user.");
但它不工作。
這是第二個選項
SELECT CASE
WHEN EXISTS (
SELECT 1
FROM [Posts] AS [p]
INNER JOIN [AspNetUsers] AS [p.User] ON [p].[UserId] = [p.User].[Id]
WHERE ([p].[Id] = @__post_Id_0) AND ([p.User].[Id] = @__currentUser_Id_1))
THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END
你能告訴我們你的發佈和用戶模型代碼嗎? – theMohammedA