Stein121
Stein121

Reputation: 109

EF Core adding object nulls a navigation property

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

Upvotes: 1

Views: 942

Answers (1)

Cristian Szpisjak
Cristian Szpisjak

Reputation: 2469

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

Upvotes: 1

Related Questions