我有许多代码块,如下所示:
modelBuilder
.Entity<Foo>()
.Property(t => t.X)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_X_Y", 1) { IsUnique = true }));
modelBuilder
.Entity<Foo>()
.Property(t => t.Y)
.IsRequired()
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_X_Y", 2) { IsUnique = true }));这个块告诉EF,通过fluent API,在表X和Y的表Foo上创建一个具有列Foo和Y的唯一索引。
另一个类似于此的代码块是这样的,表Bar上有列S和Bar。
modelBuilder
.Entity<Bar>()
.Property(t => t.R)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_R_S", 1) { IsUnique = true }));
modelBuilder
.Entity<Bar>()
.Property(t => t.S)
.IsRequired()
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_R_S", 2) { IsUnique = true }));我想重构它,这样它最终看起来就像:
CreateCompositeUnique<Foo>(modelBuilder, "IX_X_Y", t => new {t.X, t.Y});
CreateCompositeUnique<Bar>(modelBuilder, "IX_R_S", t => new {t.R, t.S});我在想这样的事情:
private void CreateCompositeUnique<T>(DbModelBuilder modelBuilder, string indexName, List<Expression<Func<T, byte[]>>> properties)
{
for (int i = 0; i < properties.Count; i++)
{
modelBuilder
.Entity<typeof(T)>()
.Property(properties[i])
.IsRequired()
.HasMaxLength(60) // --only when propery is string
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(indexName, i) { IsUnique = true }));
}
}但我有一些问题:
.Entity<typeof(T)>上得到了一个编译错误发布于 2014-10-09 21:03:59
按照Gert的建议,我创建了一个扩展方法。实际上,它们是两种扩展方法(为什么?自动解释,见代码注释)
public static class ExtensionMethods
{
public static StringPropertyConfiguration HasIndex(this StringPropertyConfiguration config, string indexName, int i)
{
return config.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation((new IndexAttribute(indexName, i) { IsUnique = true })));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration config, string indexName, int i)
{
return config.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation((new IndexAttribute(indexName, i) { IsUnique = true })));
}
}用法如下:
modelBuilder
.Entity<Foo>()
.Property(t => t.X)
.IsRequired()
.HasMaxLength(60)
.HasIndex("IX_X_Y", 1); // <-- here (X is string)
modelBuilder
.Entity<Foo>()
.Property(t => t.Y)
.IsRequired()
.HasIndex("IX_X_Y", 2); // <-- and here (Y is a primitive)https://stackoverflow.com/questions/26283537
复制相似问题