public async Task<List<Note>>ShowAssigned()
{
return await _context.Notes
.Where(x => x.List.OwnerId != x.OwnerId)
.ToListAsync()
}
我没有语法εrrors,但似乎你不能以这种方式从相关数据访问属性。
基本上,目标是:用户创建一个List,然后创建一个这个List的Notes。然后他应该能够将其中一个Notes分配给另一个用户。当其他用户登录时,他应该能够看到分配给他的新笔记。
任何人都可以帮我解决这个问题吗?
public class List
{
public Guid ListId { get; set; }
public string OwnerId { get; set; }
public List<Note> Notes { get; set; }
}
public class Note
{
public Guid ID { get; set; }
public string OwnerId { get; set; }
[ForeignKey("ListId")]
public Guid ListId { get; set; }
public List List { get; set; }
}
和上下文类:
public DbSet<Note> Notes { get; set; }
public DbSet<List> Lists { get; set; }
当我尝试在视图中以相同的方式访问数据时:
@model List<Project.Models.Note>
@foreach (var item in Model)
{
if (item.List.OwnerId == item.OwnerId)
运行Web应用程序时出现此错误(无语法错误):NullReferenceException:对象引用未设置为对象的实例
首先编写模型类,如下所示:
public class List
{
public Guid ListId { get; set; }
public string OwnerId { get; set; }
public virtual List<Note> Notes { get; set; }
}
public class Note
{
public Guid ID { get; set; }
public string OwnerId { get; set; }
[ForeignKey("List")] // Not ListId, its List
public Guid ListId { get; set; }
public virtual List List { get; set; }
}
然后编写您的查询,如下所示:
await _context.Notes.Include(n => n.List).ToListAsync()
然后在ConfigureServices()
类的Startup
方法:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
不要忘记安装适当版本的Microsoft.EntityFrameworkCore.Proxies
nuget包,因为UseLazyLoadingProxies()
位于此包中。
然后编写您的查询,如下所示:
await _context.Notes.ToListAsync()
所以我在TanvirArjel的帮助下在某些部分找到了我的问题的答案(但我基本上以不同的方式做了)
public async Task<List<Note>> GetAssignedItemsAsync(ApplicationUser user)
{
var lists = await _context.Lists.Include(l => l.Notes).Where(x => x.OwnerId != user.Id).ToListAsync();
var notesListe = new List<Note>();
foreach (List l in lists)
{
foreach (Note n in l.Notes)
{
if (n.OwnerId == user.Id)
{
notesListe.Add(n);
}
}
}
return notesListe;
}