Linq to Entity - ICollection<Guid> 错误(代码优先)

Linq to Entity - error on ICollection<Guid> (code first)

所以我们使用代码优先的方法来构建数据库。我遇到了一个问题,但解决起来收效甚微。 DB class(EF - 代码优先)

public partial class Object1
{
    [Key]
    public Guid uid { get; set; }
    public int sequenceNumber { get; set; }
    public bool triggerFlag { get; set; }
    public ICollection<Guid> Object2 { get; set; }
    public ICollection<int> Object3 { get; set; }
}

尝试检索与内部集合相关的特定条件的对象时引发错误

出错的代码我已经尝试了几种不同的 linq 方法来尝试解决错误,但 none 有效(dc 是 EF 中的 dataCOntext)

        return JsonConvert.SerializeObject(dc.Object1.Where
            (x => (!x.Object2.Any() || x.Plants.Contains(object2UID))
             && (x.Object3.Count == 0 || x.Object3.Contains(Object3)).ToList());

产生的错误是

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Additional information: The specified type member 'Object2' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

public partial class Object2
{
    [Key]
    public Guid uid { get; set; }
    [Required]
    [StringLength(50)]
    public string model { get; set; }
    [StringLength(3)]
    public string Type { get; set; }
    [StringLength(10)]
    public string alias { get; set; }
}

"no foreign keys" 规则消除了关系数据库的一大优势,但您不必使用外键即可在 EF 中将对象连接在一起。但是,如果您希望使用 EF 的导航 属性 功能,则确实需要外键。

您应该可以执行以下操作:

public partial class Object1
{
    [Key]
    public Guid uid { get; set; }
    public int sequenceNumber { get; set; }
    public bool triggerFlag { get; set; }
    public Guid Object2Id { get; set; }
    public int Object3Id { get; set; }
}

public partial class Object2
{
    [Key]
    public Guid uid { get; set; }
    [Required]
    [StringLength(50)]
    public string model { get; set; }
    [StringLength(3)]
    public string Type { get; set; }
    [StringLength(10)]
    public string alias { get; set; }
}

public partial class Object3
{
    [Key]
    public int uid { get; set; }
    // Other fields...
}

并像这样检索它们:

var objects = from o1 in dc.Object1
              join o2 in dc.Object2 on o1.Object2Id equals o2.uid
              join o3 in dc.Object3 on o1.Object3Id equals o3.uid
              select new
              {
                  Object1 = o1,
                  Object2 = o2,
                  Object3 = o3
              };

话虽如此,既然 Object1、Object2 和 Object3 之间存在关系,那么我建议使用关系数据库和 Entity Framework 它们的设计使用方式... 添加外键.