EF Core adding object nulls a navigation property

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

Question

I am trying to add a Drink object via DbContext, but after adding the drink using the context, the Brand property becomes null. What could be the reason for this?

(Ignore the double _context add method, was debugging)

Before adding the drink Before adding the drink After adding the drink After adding the drink

Models:

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
1
6/1/2017 1:34:27 PM

Accepted Answer

Your Drink model:

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

When you add a new Drink specify only the BrandId:

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

Also, EF Core does not load the related properties automatically. So if you want the Brand loaded you need to manually do it like:

var data = myContext.Drinks
    .Include(p => p.Brand)
    .FirstOrDefault(p => p.Id == yourId);
1
6/1/2017 1:30:27 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow