Reputation: 486
I've been wrestling with fluent, annotations, and combinations thereof but cannot find out why the following entities and context config generate a migration with duplicate foreign key. I've read all the other posts and tried all the suggested solutions, each one seems to be a different combo of things, but I still cannot get EF to give me a migration with one foreign key. It always generates this extra one.
public class REOProperty
{
public virtual ICollection<PropertyPhotoUrl> PropertyPhotoUrls { get; set; }
public Guid REOPropertyId { get; set; }
}
public class PropertyPhotoUrl
{
public Guid REOPropertyId { get; set; }
public virtual REOProperty REOProperty { get; set; }
public Guid PropertyPhotoUrlId { get; set; }
public string PhotoUrl { get; set; }
}
with context
public class REODbContext:DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.OneToManyCascadeDeleteConvention>();
modelBuilder.Entity<REOProperty>()
.HasKey(a => a.REOPropertyId)
.Property(a => a.REOPropertyId)
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
modelBuilder.Entity<PropertyPhotoUrl>()
.HasKey(a => a.PropertyPhotoUrlId)
.Property(a => a.PropertyPhotoUrlId)
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
modelBuilder.Entity<PropertyPhotoUrl>()
.HasRequired(a => a.REOProperty)
.WithMany(a=>a.PropertyPhotoUrls)
.HasForeignKey(a => a.REOPropertyId);
}
}
Generates a migration with duplicate foreign keys on the child
PropertyPhotoUrl
entity.
CreateTable(
"dbo.PropertyPhotoUrls",
c => new
{
PropertyPhotoUrlId = c.Guid(nullable: false, identity: true),
REOPropertyId = c.Guid(nullable: false),
PhotoUrl = c.String(),
REOProperty_REOPropertyId = c.Guid(),
})
.PrimaryKey(t => t.PropertyPhotoUrlId)
.ForeignKey("dbo.REOProperties", t => t.REOPropertyId)
.ForeignKey("dbo.REOProperties", t => t.REOProperty_REOPropertyId)
.Index(t => t.REOPropertyId)
.Index(t => t.REOProperty_REOPropertyId);
I've seen this issue before and usually can resolve by changing up the fluent code. If I try to manual edit the migration to get what I want then the ef throws exceptions when I make queries.
Am I doing something wrong here?
Upvotes: 0
Views: 641
Reputation: 1522
use this :
public class REOProperty
{
[InverseProperty("REOProperty")]
public virtual ICollection<PropertyPhotoUrl> PropertyPhotoUrls { get; set; }
public Guid REOPropertyId { get; set; }
}
public class PropertyPhotoUrl
{
public Guid REOPropertyId { get; set; }
[ForeignKey("REOPropertyId")]
[InverseProperty("PropertyPhotoUrls")]
public virtual REOProperty REOProperty { get; set; }
public Guid PropertyPhotoUrlId { get; set; }
public string PhotoUrl { get; set; }
}
Upvotes: 2