EF Core添加对象使导航属性为空

时间:2017-06-01 13:20:20

标签: c# asp.net-core entity-framework-core

我正在尝试通过DbContext添加Drink对象,但在使用上下文添加饮料后,Brand属性变为null。 这可能是什么原因?

(忽略double _context add方法,正在调试)

Before adding the drink 在加入饮料之前 After adding the drink 加入饮料后

型号:

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; }
}

1 个答案:

答案 0 :(得分:0)

你的饮料模特:

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);
相关问题