【发布时间】:2021-07-01 12:11:19
【问题描述】:
我正在尝试获取实体User 的整个图表。 User 类是:
更新
public class User
{
[Key]
public int Id { get; set; }
public string email_address { get; set; }
[Column("Password Hash")]
public string PasswordHash { get; set; }
public string custnmbr { get; set; }
public Customer Customer { get; set; }
}
我的Customer班级:
public class Customer
{
[Key]
public string Custnmbr { get; set; }
public string Custname { get; set; }
public ICollection<User> Users { get; set; }
}
我的 DbContext 中有这个:
public class EntityContext : DbContext
{
public EntityContext(DbContextOptions<EntityContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOne<Customer>(u => u.Customer)
.WithMany(c => c.Users)
.HasForeignKey(u => u.custnmbr);
}
}
我的用户服务:
public class UserService : IUserService
{
private readonly EntityContext _context;
public UserService(EntityContext context)
{
_context = context;
_context.Users.Include("Customer").Load();
}
public IEnumerable<User> GetAll()
{
var users = _context.Users.Local.ToList();
return users;
}
public User GetByUsername(string emailAddress)
{
var user = _context.Users.Local.SingleOrDefault(x => x.email_address == emailAddress);
return user;
}
}
我的用户控制器:
[Route("api/Users")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet("GetAll")]
public IActionResult GetAll()
{
var users = _userService.GetAll();
return Ok(users);
}
[HttpGet("GetUser")]
public IActionResult GetUser(string emailAddress)
{
var user = _userService.GetByUsername(emailAddress);
return Ok(user);
}
}
GetAll() 返回所有Users 的整个图。但是 GetUser() 返回一个 User 属性为空的 Customer。
如何获得包括属性Customer 在内的整个User 图表?
任何帮助将不胜感激。
Microsoft Visual Studio 社区 2019 - 版本 16.10.3
Microsoft.AspNetCore (5.0.0)
Microsoft.EntityFrameworkCore (5.0.7)
【问题讨论】:
-
不是因为
NotMapped属性显式设置在Customer属性上吗? -
@Crono,我删除了
NotMapped和Customer属性仍然为空。 -
您需要创建一个新的迁移并在删除
[NotMapped]属性后应用它。 -
@LazZiya 我没有使用迁移
-
很可能“加载”会忽略“包含”。加载的想法是“加载”一种类型的实体,因此您应该分别加载客户和用户,然后在执行实际查询时才包含
标签: c# asp.net-core entity-framework-core