In this context, only primitive or enumeration types are supported in ASP.NET MVC with Entity Framework

I am creating a sample ASP.NET MVC web application and I am executing the first code approach for a database. I want to create a table productstable and transactions, and in addition, I want to include some sample data through migrations, but when I tried to do it Update-Database, I got the error message mentioned in the header. I know exactly why the error occurs, and because I use List<Product>, as seen below. But I do not know how I can solve the problem, while transactions should include one or more products. My code segments can be found below.

public class Product
{
    public int ProductID { get; set; }

    public string Name { get; set; }

}

public class Transaction
{
    public int TransactionID { get; set; }

    public List<Product> Products { get; set; }

}

I also added the following lines of code to the file IdentityModels.cs:

public DbSet<Product> Products { get; set; }

public DbSet<Transaction> Transactions { get; set; }

, Configuration.cs, , :

public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}

protected override void Seed(MyApp.Models.ApplicationDbContext context)
{
    var pr = new List<Product>();
    pr.Add(new Product { Name = "Book" });
    pr.Add(new Product { Name = "Table" });
    pr.Add(new Product { Name = "Chair" });

    pr.ForEach(i => context.Products.AddOrUpdate(p => p.Name, i));
    context.SaveChanges();

    context.Transactions.AddOrUpdate(
        t => t.Products,
        new Transaction { Products = new List<Product>(pr.Where(p => p.Name == "Book" || p.Name == "Table")) },
        new Transaction
        {
            Products = new List<Product>(pr.Where(p => p.Name == "Chair" || p.Name == "Book" || p.Name == "Table"))
        }
    );

    context.SaveChanges();
}
+4
1

- AddOrUpdate, .. identifierExpression. , , . identifierExpression, ​​ , . , .

t.Products , , , , , Products, , , Products . , ( , ).

context.Transactions.AddOrUpdate(
    //t => t.Products,   //comment this
    new Transaction { 
        Products = new List<Product>(
                        pr.Where(p => p.Name == "Book" || p.Name == "Table")) 
    },
    new Transaction
    {
        Products = new List<Product>(
                pr.Where(p => p.Name == "Chair" || p.Name == "Book" || p.Name == "Table"))
    }
);

Seed , Transaction Product . , EF. , . ( Context):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<Transaction>().HasMany(x => x.Products).WithMany();
}

, , Products Transaction virtual.

+1

Source: https://habr.com/ru/post/1648927/


All Articles