EF关系-由于list <guid>是原始的,因此无法映射

时间:2018-07-24 13:51:51

标签: c# entity-framework .net-core ef-core-2.0

我想存储在User类的Item集合中

但是我无法克服这个问题:

  

System.InvalidOperationException:'属性'User.ItemsIds'无法映射,因为它的类型为'List',它不是受支持的原始类型或有效实体类型。要么显式映射此属性,要么使用“ [NotMapped]”属性或“ OnModelCreating”中的“ EntityTypeBuilder.Ignore”忽略它。

我正在使用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");
    }
}

这里有类似的问题,但是还没有“解决”吗?

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

3 个答案:

答案 0 :(得分:4)

您不能仅存储从属实体标识符。
主要实体User必须具有Item的集合:

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

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

    // ...
}

答案 1 :(得分:0)

如何在集合中使用Item对象代替itemID,并使用Fluent API将这种关系一对多映射。使用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);
}

答案 2 :(得分:0)

尝试使用icollection代替列出并映射到显式代码

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....