EF Core添加對象使導航屬性為空

asp.net-core c# entity-framework-core

我試圖通過DbContext添加一個Drink對象,但在使用上下文添加飲料後,Brand屬性變為null。這可能是什麼原因?

(忽略double _context add方法,正在調試)

在加入飲料之前在加入飲料之前加入飲料後加入飲料後

楷模:

public class Product
{
    [Key]
    public string Id { get; set; }
    public string Name { get; set; }
}

public class Drink : Product
{
    public Brand Brand { get; set; }
    public Category Category { get; set; }
    public ICollection<DrinkTag> DrinkTags { get; set; }
}


public class Brand
{
    [Key]
    public string Name { get; set; }

    public ICollection<Drink> Drinks { get; set; }
}

public class Category
{
    [Key]
    public string Name { get; set; }

    public ICollection<Drink> Drinks { get; set; }
}

public class Tag
{
    [Key]
    public string Name { get; set; }

    public ICollection<Drink> Drinks { get; set; }
}

public class DrinkTag
{
    public string DrinkId { get; set; }
    public Drink Drink { get; set; }
    public string TagId { get; set; }
    public Tag Tag { get; set; }
}

一般承認的答案

你的飲品型號:

public class Drink : Product
{
    public int BrandId { get; set; }

    // Navigational properties
    public Brand Brand { get; set; }
    public Category Category { get; set; }
    public ICollection<DrinkTag> DrinkTags { get; set; }
}

添加新飲品時,僅指定BrandId:

var myDrink = new Drink();
myDrink.BrandId = 2;
// ... and so on

此外,EF Core不會自動加載相關屬性。因此,如果您想要加載品牌,您需要手動執行以下操作:

var data = myContext.Drinks
    .Include(p => p.Brand)
    .FirstOrDefault(p => p.Id == yourId);


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow