public async Task<List<Note>>ShowAssigned()
{
return await _context.Notes
.Where(x => x.List.OwnerId != x.OwnerId)
.ToListAsync()
}
Non ottengo sintassi di sintassi, ma sembra che tu non possa accedere agli attributi dai dati correlati in questo modo.
Fondamentalmente l' obiettivo è: un utente crea una lista, quindi alcune note per questo elenco. Quindi dovrebbe essere in grado di assegnare una di quelle note a un altro utente. Quando l'altro utente si collega, dovrebbe essere in grado di vedere quella nuova nota che gli è stata assegnata.
Qualcuno può aiutarmi con questo?
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; }
}
E la classe di contesto:
public DbSet<Note> Notes { get; set; }
public DbSet<List> Lists { get; set; }
Quando provo ad accedere ai dati nello stesso modo in una vista del genere:
@model List<Project.Models.Note>
@foreach (var item in Model)
{
if (item.List.OwnerId == item.OwnerId)
ottengo questo errore durante l'esecuzione dell'app Web (nessun errore di sintassi): NullReferenceException: il riferimento all'oggetto non è impostato su un'istanza di un oggetto
Così ho trovato la risposta al mio problema, in alcune parti con l'aiuto di TanvirArjel (ma fondamentalmente l'ho fatto in modo diverso)
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;
}
Per prima cosa scrivi le tue classi modello come segue:
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; }
}
Quindi scrivi la tua richiesta come segue:
await _context.Notes.Include(n => n.List).ToListAsync()
Quindi nel metodo ConfigureServices()
nella classe Startup
:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Non dimenticare di installare la versione appropriata del pacchetto nuget Microsoft.EntityFrameworkCore.Proxies
perché UseLazyLoadingProxies()
trova in questo pacchetto.
Quindi scrivi la tua richiesta come segue:
await _context.Notes.ToListAsync()