How do I include a complex type to an Entity Index?

天涯浪子 提交于 2019-12-24 12:44:13

问题


I have these 2 POCOs...

public class SqlTrace
{
    public int id { get; set; }
    public string Name { get; set; }
    public virtual List<SqlTraceFile> TraceFiles { get; set; }
}

public class SqlTraceFile
{
    public int id { get; set; }
    public string Name { get; set; }
    public virtual SqlTrace Trace { get; set; }
}

I created a 1 to many relationship between the trace and its files. I want to add an index that would make it so that SqlTraceFiles are unique to its SqlTrace; Allow multiple SqlTraceFiles to be named the same as long as they belong to a different SqlTrace.

Below is what I have within the SqlTraceFileConfiguration : EntityTypeConfiguration< SqlTraceFile >

Property(TraceFile => TraceFile.Name)
            .IsRequired()
            .HasColumnAnnotation("Index", new IndexAnnotation(
                new IndexAttribute("IX_SQLTracefile_FileTrace", 1) { IsUnique = true }
                ));
Property(TraceFile => TraceFile.Trace)
            .HasColumnAnnotation("Index", new IndexAnnotation(
                new IndexAttribute("IX_SQLTracefile_FileTrace", 1) { IsUnique = true }
                ));

My problem is that it doesn't take the 'tracefile => tracefile.trace' I am guessing that entity want the foreign key in place of 'tracefile.trace'. Is there a pattern I must follow to accomplish this? Or a workaround to my position.


回答1:


Try this as your poco's:

public class SqlTrace
{
    public int Id { get; set; }

    //added indexes with annotations
    [Index("otherNameIndex", IsUnique = true)]
    public string Name { get; set; }

    //changed to ICollection
    public virtual ICollection<SqlTraceFile> TraceFiles { get; set; }
}

public class SqlTraceFile
{
    public int Id { get; set; }
    [Index("nameIndex", IsUnique = true)]
    public string Name { get; set; }

    //added the FK id property explicit and put an index on to it.
    [Index("indexname", IsUnique = true)]
    public int SqlTraceId {get;set;}
    public virtual SqlTrace Trace { get; set; }
}

You won't need the fluent code this way.



来源:https://stackoverflow.com/questions/35489396/how-do-i-include-a-complex-type-to-an-entity-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!