I have the following model:
public class Retailer : Entity
{
public string Name { get; set; }
public string Address { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public class Product : Entity
{
public string Name { get; set; }
public string Description { get; set; }
public string ECommerceUrl { get; set; }
public string ImageUrl { get; set; }
public Retailer Retailer { get; set; }
public ICollection<Category> Categories { get; set; }
}
I'm trying to define a 1 to (0 or many) relationship where a retailer can have 0 or multiple products with the following:
modelBuilder.Entity<Product>()
.HasRequired(r => r.Retailer)
.WithMany(p => p.Products)
.HasForeignKey(p => p.Id); // Id is defined in the base class
I'm getting the error
Product_Retailer_Source: : Multiplicity is not valid in Role 'Product_Retailer_Source' in relationship 'Product_Retailer'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.
What is wrong with how I'm defining the relationship? How can I fix this?
Try this
public class Product : Entity
{
public Retailer Retailer { get; set; }
public int RetailerId { get; set; }
}
With this configuration (you didn't have a foreign key defined to store the RetailerId against the Product)
modelBuilder.Entity<Product>()
.HasRequired(r => r.Retailer)
.WithMany(p => p.Products)
.HasForeignKey(p => p.RetailerId);