如何将自定义类设置为实体框架中的实体的唯一

时间:2016-05-25 07:09:39

标签: c# entity-framework

使用实体框架6处理WPF项目。

我的自定义类包含2个需要唯一的字段(在id之上)。 一个是字符串类型,另一个是自定义类型。

实体类的实现如下:

public partial class MyEntity
{
    [Key]
    public int Id { get; set; }

    [MaxLength(100)]
    [Index(IsUnique = true)]
    public string Name{ get; set; }

    [MaxLength(100)]
    [Index(IsUnique = true)]
    public MyClass myClass { get; set; }
...
}

然后,当我托盘通过以下方式添加新的MyEntity时:

context.SaveChanges();

我得到了这个例外:

  Message=Unable to create a constant value of type 'NS.MyClass '. Only primitive types or enumeration types are supported in this context.
  Source=EntityFramework

注意:如果我评论MyClass声明的属性,则另一个唯一字段(Name)不会生成异常。

真的没有办法将自定义类设置为实体的唯一吗?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

在实体框架6中,您必须自己完成此操作。在这里查看我的灵魂:Unique Key constraints for multiple columns in Entity Framework