3

I'd want to store in User class collection of Items

But I cannot overcome this problem:

System.InvalidOperationException: 'The property 'User.ItemsIds' could not be mapped, because it is of type 'List' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

I'm using ASP.NET Core 2.0 + EFCore

public class User
{
    [Key]
    public Guid Id { get;  set; }
    [ForeignKey("Items")]
    public virtual List<Guid> ItemsIds{ get; set; }
    (...)
}

public class Item
{
    [Key]
    public Guid Id { get;  set; }
    public string ItemName { get; set; }
    public Item(string name)
    {
        Id = new Guid();
        ItemName = name;
    }
}

public class AppContext : DbContext
{
    public AppContext(DbContextOptions<AppContext> options) : base(options)
    {   
        Database.SetCommandTimeout(35000);
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Item> Items { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().ToTable("Users");
        modelBuilder.Entity<Item>().ToTable("Items");
    }
}

Here's similar problem, but still it hasn't been "fixed"?

Entity Framework - Code First - Can't Store List<String>

UbuntuCore
  • 409
  • 7
  • 20
  • What database are you targeting? How would you want to store a list of GUIDs in the underlying database structure? Think about how an RDBMS only store single (scalar) values in each field/column. – Dai Jul 24 '18 at 15:06
  • @Dai I'm targeting MSSQL – UbuntuCore Jul 25 '18 at 07:33

3 Answers3

4

You can't store dependent entity identifiers only.
Principal entity User must have collection of Item:

public class User
{
    [Key]
    public Guid Id { get;  set; }

    public virtual List<Item> Items { get; set; }

    // ...
}
Dennis
  • 37,026
  • 10
  • 82
  • 150
0

how about use Item object in the collection instead of itemIDs and use the Fluent API to map the relationship one to many. use Has/With pattern to configure One To Many Relationships in Entity Framework Core

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Employee> Employees { get; set; }
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Company Company { get; set; }
}

protected override void OnModelCreating(Modelbuilder modelBuilder)
{
    modelBuilder.Entity<Company>()
        .HasMany(c => c.Employees)
        .WithOne(e => e.Company);
}
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51
0

try to use icollection instead list and map to explicit code

class Item{public virtual User User{get;set;};public Guid UserId{get;set;}}

modelbuilder.Entity<Item>.HasOne(s => s.User)
          .WithMany(n => n.ItemsIds).HasForeignKey....
Amin Sahranavard
  • 268
  • 1
  • 10