首页 > 解决方案 > 使用 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

标签: c#entity-framework-core

解决方案


要获取具有关系的实体,您应该Include像这样使用:

var stuff = _context.Stuff.Include(x=>x.OtherStuff).First();
var otherStuffName=stuff.OtherStuff.OtherStuffName;

无需OtherStuffNameStuff实体中添加属性,因为它在 OtherStuff 实体中。


推荐阅读