在EF Core中使用拥有的实体生成复合的唯一约束/索引 [英] Generate a composite unique constraint/index with owned entity, in EF Core

查看:596
本文介绍了在EF Core中使用拥有的实体生成复合的唯一约束/索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个拥有另一个实体的实体

I have an entity that owns another entity

public class Entity1
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public virtual int ID { get; set; }

  public string Property { get; set; }

  public Entity2 Description { get; set; }
}

public class Entity2
{
   public string Test { get; set; }
}

,我需要在Entity1.Property和Entity2.Test上创建索引。配置是这样的

and I need to create an index on Entity1.Property and Entity2.Test. The configuration is like this

builder.OwnsOne(pt => pt.Description);

builder.HasIndex(p => new { p.Property, p.Description.Test }).IsUnique();
//builder.HasIndex("Property", "Description_Test").IsUnique();

我尝试了以上两个代码,但它们均无效。第一个说

I tried both of the above code but they do not work. The first says

The properties expression 'p => new <>f__AnonymousType3`7(Property = p.DeviceClassId, 
Test = p.Description.Test)' is not valid. The expression should represent a property 
access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type:
't => new { t.MyProperty1, t.MyProperty2 }'.
Parameter name: propertyAccessExpression

,第二个输入:

The property 'Description_test' cannot be added to the type 'Entity1' because there was no 
property type specified and there is no corresponding CLR property or field. To add a 
shadow state property the property type must be specified.

是否可以在不手动修改迁移的情况下实现?

Can this be achieved without modifying the migration manually?

推荐答案

显然EF Core还不支持此功能。

Apparently EF Core doesn't support this feature yet.

在GitHub上查看此问题:
https://github.com/aspnet/EntityFrameworkCore/issues/11336

See this issue on GitHub: https://github.com/aspnet/EntityFrameworkCore/issues/11336

还提供了一种解决方法,我没有进行自我测试。

There is also a workaround offered, which I have not tested myself.

这篇关于在EF Core中使用拥有的实体生成复合的唯一约束/索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆