2016-02-18 47 views
1

我有這2個波蘇斯...如何將複雜類型包含到實體索引?

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; } 
} 

我創建了一個1到跟蹤和文件之間一對多的關係。我想添加一個索引,使得SqlTraceFiles對於它的SqlTrace是唯一的;只要它們屬於不同的SqlTrace,就允許多個SqlTraceFiles命名相同。

下面是我有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 } 
       )); 

我的問題是,它並沒有採取「跟蹤文件=> tracefile.trace」我猜測實體希望外國鍵代替'tracefile.trace'。有沒有一種模式可以實現這一點?或者解決我的立場。

+0

你可以用這裏提到的屬性創建索引:http://stackoverflow.com/questions/16853909/create-database-index-with-entity-framework/21743868#21743868 – Stefan

+0

你可以把索引放在一個明確的創建FK屬性 – Stefan

+0

有沒有辦法使用Fluent API而不是DataNotation? – Hakubex

回答

1

試試這個作爲你的POCO的:

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; } 
} 

你並不需要流利的代碼這種方式。

+1

我接受了答案......我真的希望用FluentAPI來完成它。你確實提到我可以明確地添加外鍵,我不知道你可以這樣做。我認爲這將是我的方法。非常感謝您的快速回復和答覆。 – Hakubex

+0

沒有問題,如果你找到了流暢的方式;你總是可以將它發佈爲答案。我相信你會得到一些upvotes :-) – Stefan

+0

@Hakubex:作爲最後的評論:在這種情況下'SqlTraceId'被設置爲'SqlTrace'的命名約定('SqlTrace' +'Id')的關鍵。你也可以選擇一個任意的名字,但是你需要'[ForeignKey]'屬性。 – Stefan