问题
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