I have a Product class:
public class Product
{
public int ID { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
public Offer Offer { get; set; }
}
And an Offer class:
public class Offer
{
public int ID { get; set; }
[Required]
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public decimal OfferPrice { get; set; }
public Product Product { get; set; }
}
Basically want I want to achieve is when an offer is added a Product is related to this Offer. So an Offer always has a Product but a Product does not always need an Offer. If the Product does have an Offer I'd like to be able to access it through Product.Offer
, but in this setup I get the following error message when updating the database:
Unable to determine the principal end of an association between the types 'WebshopISEC.Models.Offer' and 'WebshopISEC.Models.Product'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
I've tried a lot of things (data annotations and Fluent API) and searched endlessly but I cannot seem to solve this issue. A Fluent API approach I've tried:
modelBuilder.Entity<Offer>()
.HasRequired(x => x.Product)
.WithOptional(x => x.Offer);
But this worked to no avail, how do I assign a Principal End? And to what class?
Try this:
public class Product
{
public int ID { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
public Offer Offer { get; set; }
}
public class Offer
{
[ForeignKey("Product")]
public int ID { get; set; }
[Required]
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public decimal OfferPrice { get; set; }
public Product Product { get; set; }
}