【发布时间】:2016-10-10 03:39:01
【问题描述】:
我想在多个列上放置索引(如this question 中所述),但其中一个属性是模型中没有外键属性的导航属性。
TL;DR 在底部。
我的模特:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public virtual Shop Shop { get; set; }
}
public class Shop
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Shop> Shops { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasRequired(u => u.Shop).WithMany();
modelBuilder.Entity<User>().Property(u => u.Email).HasMaxLength(256);
}
}
我使用了一个扩展(基于前面提到的问题):
internal static class ModelBuilderExtensions
{
public static StringPropertyConfiguration AddMultiColumnIndex(this StringPropertyConfiguration config, string indexName, int columnOrder, bool unique = false, bool clustered = false)
{
var indexAttribute = new IndexAttribute(indexName, columnOrder) { IsUnique = unique, IsClustered = clustered };
var indexAnnotation = new IndexAnnotation(indexAttribute);
return config.HasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation);
}
public static PrimitivePropertyConfiguration AddMultiColumnIndex(this PrimitivePropertyConfiguration property, string indexName, int columnOrder, bool unique = false, bool clustered = false)
{
var indexAttribute = new IndexAttribute(indexName, columnOrder) { IsUnique = unique, IsClustered = clustered };
var indexAnnotation = new IndexAnnotation(indexAttribute);
return property.HasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation);
}
}
我希望创建一个索引如下:
modelBuilder.Entity<User>().Property(x => x.Email).AddMultiColumnIndex("UX_User_EmailShopId", 0, unique: true);
modelBuilder.Entity<User>().Property(x => x.Shop.Id).AddMultiColumnIndex("UX_User_EmailShopId", 1, unique: true);
但这在构建迁移时给了我一个错误:
System.InvalidOperationException: 'Shop' 类型已经存在 配置为实体类型。它不能重新配置为复合体 输入。
当我尝试按如下方式添加索引时,会出现另一个错误:
modelBuilder.Entity<User>().Property(x => x.Shop).AddMultiColumnIndex("UX_User_EmailShopId", 1, unique: true);
类型“My.NameSpace.Shop”必须是不可为空的值类型 为了将其用作泛型类型或方法中的参数“T” 'System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration.Property(System.Linq.Expressions.Expression>)
TL;DR
所以我的问题是,当我的模型中没有定义 shop_id(我不想定义它)时,如何使用 fluent-api 在电子邮件和商店(id)组合上添加索引?
生成的 SQL 应该类似于:
CREATE UNIQUE NONCLUSTERED INDEX [UX_User_EmailShopId] ON [dbo].[User]
(
[Email] ASC,
[Shop_Id] ASC
)
【问题讨论】:
标签: c# entity-framework ef-code-first entity-framework-migrations ef-fluent-api