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

ef-code-first entity-framework-6

Accepted Answer

based on the model,Product has two many-to-one FK connections toUser - From 1 throughCreatedBy between 1 andModifiedBy . Though, theUser class includes only oneProducts collection, but EF just needs a for every connection for one or no matching navigation property. Additionally, it attempts quietly to construct a third connection since it is unsure to which of the existing FK that collection is intended to be mapped. Because the default mapping is ineffective in these circumstances, you must useInverseProperty or fluid API to properly express the mappings.

The bidirectional mapping, for instance, may be described as follows:

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 aforementioned resolves the mapping problem, it also creates a new problem known as a number of cascade pathways since, according to EF norms, cascade delete is enabled for one-to-many relationships by default. Remove the cascade delete for one or both relationships as you must use fluent configuration to do so.ForeignKey and InverseProperty annotations and fluidly configure everything:

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);
2
6/5/2017 9:05:17 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow