【问题标题】:How to set a custom class as Unique into an Entity in Entity Framework如何将自定义类设置为唯一到实体框架中的实体
【发布时间】:2016-05-25 16:12:40
【问题描述】:

使用实体框架 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 声明的属性,其他唯一字段(名称)不会生成异常。

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

提前致谢。

【问题讨论】:

标签: c# entity-framework


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    相关资源
    最近更新 更多