Schema specified is not valid. Errors: The relatio

2019-09-16 09:54发布

问题:

I have following code first models and I try to initialized database it giving me error mention below. One user can have multiple products so there is one to many relationship between user and product.

Schema specified is not valid. Errors: The relationship 'Models.Product_CreatedByUser' was not loaded because the type 'User' is not available.

I am using code first approach, can any one help me with this.

User:

public class User
{
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<Product> Products { get; set; }
} 

Product:

public class Product
    {
    public long ProductId { get; set; }
    public string ProductCode { get; set; }
    public string Name { get; set; }
    public DateTime CreatedDate { get; set; }
    public long CreatedBy { get; set; }
    public long ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
    public bool IsDeleted { get; set; }
    [ForeignKey("CreatedBy")]
    public virtual User CreatedByUser { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User ModifiedByUser { get; set; }
}

回答1:

According to the model, Product has 2 many-to-one FK relationships to User - 1 through CreatedBy and 1 through ModifiedBy. However, the User class contains a single Products collection, while EF requires one or zero corresponding navigation property for each relationship. Also, it doesn't know to which of the current FK is supposed to map that collection, so it silently tries to create a 3rd relation :( Since the default mapping doesn't work for such scenarios, you need to use InverseProperty or fluent API to specify the mappings correctly.

For instance, the bidirectional mapping can be specified like this:

public class User
{
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [InverseProperty("CreatedByUser")]
    public virtual ICollection<Product> CreatedProducts { get; set; }
    [InverseProperty("ModifiedByUser")]
    public virtual ICollection<Product> ModifiedProducts { get; set; }
}

Upate: While the above fixes the mapping issue, it introduces another issue known as multiple cascade paths, because by the default EF conventions cascade delete is on for one-to-many relationships. Since you need fluent configuration anyway to turn the cascade delete off for one or both relationships, you'd better remove ForeignKey and InverseProperty annotations and configure the whole thing fluently:

modelBuilder.Entity<Product>()
    .HasRequired(e => e.CreatedByUser)
    .WithMany(e => e.CreatedProducts)
    .HasForeignKey(e => e.CreatedBy)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Product>()
    .HasRequired(e => e.ModifiedByUser)
    .WithMany(e => e.ModifiedProducts)
    .HasForeignKey(e => e.ModifiedBy)
    .WillCascadeOnDelete(false);