1

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; }
}
3
  • Forget the navigation property, can you explain why drink.Name property changed? Commented Jun 11, 2017 at 7:22
  • @Smit I didn't notice that. These 2 screenshots were right after each other. I definitely was not changing anything via the watch list so I have no idea how it could have changed. Commented Jun 12, 2017 at 9:56
  • Can you share more code about your controller? Especially the method being called & how the DbContext is being injected Commented Jun 12, 2017 at 17:17

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I am not loading, I am creating.
Where's your relation defined between those 2 tables?
The adding of the brand via a BrandId property works but do you know why the navigation property would be null after adding it via the context?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.