c# - 使用 EF Core 如何进行简单的连接以获得一个值
问题描述
我正在使用 EF Core 3.1.6。我有两个模型类:
[Table("Stuff")]
public class Stuff
{
[Key]
public int StuffId {get;set;}
public string NameOfStuff {get;set;}
public int OtherStuffId {get;set;}
///this is what I want from the other model
public string OtherStuffName {get; set;}
public OtherStuff OtherStuff {get;set;}
}
[Table("OtherStuff")]
public class OtherStuff
{
[Key]
public int OtherStuffId {get;set;}
public string OtherStuffName {get;set;}
public ICollection<Stuff> Stuff {get;set;}
}
在我的dbcontext
我有:
public DbSet<Stuff> Stuffs {get;set;}
public DbSet<OtherStuff> OtherStuffs {get;set;}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// I'm not really sure what to do here???
// I've tried this
modelBuilder.Entity<Stuff>()
.HasOne<OtherStuff>(s => s.OtherStuff)
.WithMany(g => g.Stuff)
.HasForeignKey(s => s.OtherStuffId);
}
这将为“OtherStuff”返回一个空数据集——这不是我想要的。有什么帮助吗?
这是如何调用它的示例:
var stuff = _context.Stuff.OtherStuffName; //this is null
var stuffList = _context.Stuff.OtherStuff; //this is null
解决方案
要获取具有关系的实体,您应该Include
像这样使用:
var stuff = _context.Stuff.Include(x=>x.OtherStuff).First();
var otherStuffName=stuff.OtherStuff.OtherStuffName;
无需OtherStuffName
在Stuff
实体中添加属性,因为它在 OtherStuff 实体中。
推荐阅读
- java - cameraX 对焦不准确
- javascript - 如何设置特定文本输入不需要填写
- javascript - 在 div 中的所有元素上设置文本颜色
- c - 我希望 ac 程序找到我使用数组编写的最大和最小数字有人可以帮助我如何在不使用数组的情况下制作
- spring - 具有一个实体的两列的 Spring Boot Data JPA 方法
- android - Android - 默认情况下折叠通知操作
- gradle - 如何使用 Junit5 和 Jacoco 配置 build.gradle 以进行测试覆盖
- python - python import pymssql:未加载库:libsybdb.5.dylib
- c++ - 在 SPOJ 上出现运行时错误(SIGSEGV),无法找出我的代码有什么问题
- python - 通过分组值创建新列的最佳方法是什么?