问题
I'm trying to create a billing database with Entity Framework 4.3 using Code First with Data Annotations, and I'm getting an error every time I try to create my database. Here are the objects that I'm dealing with:
public class ClientBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientID { get; set; }
[Required]
public string ClientName { get; set; }
[Required]
public bool IsActive { get; set; }
[Required]
public string ClientContactName { get; set; }
[Required]
public string ClientContactEmail { get; set; }
public virtual List<PropertyBase> Communities { get; set; }
}
public class PropertyBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PropertyID { get; set; }
[ForeignKey("Client")]
public int ClientID { get; set; }
[Required, EnumDataType(typeof(BillingFrequency))]
public BillingFrequency PropertyBillingFrequency { get; set; }
[Required]
public bool IsActive { get; set; }
[Required]
public string PropertyName { get; set; }
public string PropertyStreet { get; set; }
public string PropertyCity { get; set; }
public string PropertyState { get; set; }
public int PropertyZipCode { get; set; }
public virtual ClientBase Client { get; set; }
}
No matter what I try to do, I always get this error:
The operation failed because an index or statistics with name 'IX_ClientID' already exists on table 'Property'.
I've seen solutions to this question with the Fluent API, but I haven't found one for Data Annotations.
Does anyone have any idea how to fix this?
EDIT: Here is the code in the DbContext:
public DbSet<ClientBase> ClientBases { get; set; }
public DbSet<PropertyBase> PropertyBases { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
回答1:
Fixed it. It turned out that I had forgotten that there was another class that I had made that had a Foreign Key relationship to ClientBase. I forgot to bring that into ClientBase as a virtual property and Entity Framework was not happy with me. When I included it, it worked perfectly.
Thank you both for your help!
来源:https://stackoverflow.com/questions/10438219/index-already-exists-error-in-ef-4-3-code-first-with-data-annotations