Home > Mobile >  One-To-Many where One can reference already existing Many in EF5?
One-To-Many where One can reference already existing Many in EF5?

Time:02-13

I have a table called Products that have a Collection of Categories, giving the models like this:

public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public ICollection<Category> Categories { get; set; }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
}

Entity base provides some additional properties like Id

When running the migrations, EF creates a ProductId FK in the Category SQL table, so it can't hold multiple products.

The desired functionality is to have multiple Products referecing the same Category, how can be this done with One-To-Many relationship?

CodePudding user response:

if you want one category has many product you should do :

public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
    public ICollection<Product > Products { get; set; }
}

CodePudding user response:

try to add

public Product Product { get; set; }

property to Category

and add a method in Product for categories

public class Product : EntityBase
{
    public string Name { get; set; }
    public float Price { get; set; }
    public ICollection<Category> Categories { get; set; }
    
    public Product () 
    {
        Categories = new Collection<Category>();
    }
}

public class Category : EntityBase
{
    public string Name { get; set; }
    public User User { get; set; }
}

then

modelBuilder.Entity<Category>().HasRequired(n => n.Product)
            .WithMany(n=>n.Categories)
            .HasForeignKey(n => n.ProductId)
            .WillCascadeOnDelete(true);

in OnModelCreating(DbModelBuilder modelBuilder) in the context definition

Then regenerate Database

  • Related