2
我有兩個模型,一個模型連接兩個。ASP.NET核心與實體框架多對多不工作
Organization
型號:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Verbonding.Models
{
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<OrganizationApplicationUser> OrganizationApplicationUsers { get; set; }
public Organization()
{
IsActive = true;
IsBlocked = false;
DateCreated = DateTime.Now;
DateUpdated = DateTime.Now;
}
public ApplicationUser AddUser(ApplicationUser user)
{
OrganizationApplicationUser ou = new OrganizationApplicationUser { ApplicationUser = user, Organization = this };
OrganizationApplicationUsers.Add(ou);
return user;
}
}
}
ApplicationUser
型號:
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Linq;
namespace Verbonding.Models
{
public class ApplicationUser : IdentityUser
{
public bool IsActive { get; set; }
public IQueryable<OrganizationApplicationUser> OrganizationApplicationUsers { get; set; }
public ApplicationUser():base()
{
IsActive = true;
IsBlocked = false;
DateJoined = DateTime.Now;
DateUpdated = DateTime.Now;
}
public IQueryable<Organization> GetOrganizations()
{
return OrganizationApplicationUsers.Select(x => x.Organization);
; }
}
}
DbContext
:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Verbonding.Models;
namespace Verbonding.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<OrganizationApplicationUser>().HasKey(x => new { x.OrganizationId, x.ApplicationUserId });
}
public DbSet<Country> Countries { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<Organization> Organizations { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<OrganizationApplicationUser> OrganizationApplicationUsers { get; set; }
}
}
經過一番研究,我也添加了這個代碼到OnModelCreating
方法。
builder.Entity<OrganizationApplicationUser>()
.HasOne(ou => ou.Organization)
.WithMany(o => o.OrganizationApplicationUsers)
.HasForeignKey(ou => ou.Organization);
builder.Entity<OrganizationApplicationUser>()
.HasOne(ou => ou.ApplicationUser)
.WithMany(u => u.OrganizationApplicationUsers)
.HasForeignKey(ou => ou.ApplicationUserId);
使用我發現OrganizationApplicationUsers
調試器仍然null
。
我能做些什麼來解決這個問題?
你的命名比較混亂。你的意思'Organization.OrganizationApplicationUsers'或'ApplicationDbContext.OrganizationApplicationUsers'仍然爲空? –
*當*是否保留爲空?如果您希望它延遲加載 - 這還沒有(支持)。 –