Reputation: 258
These are my models:
public class Application
{
public Guid ID { get; set; }
public virtual Project MainProject { get; set; }
public virtual ICollection<Solution> Solutions { get; set; }
}
public class Solution
{
public Guid Id { get; set; }
public virtual Application Application { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
public class Project
{
public Guid Id { get; set; }
public virtual ICollection<Solution> Solutions { get; set; }
}
So basically, an Application has a list of Solutions, and a Solution has a list of Projects. An Application also has a Main Project (which will be somewhere in the group of Projects that is accessible through the Application's Solutions, but that's not forced by the DB).
I've got an issue when I try to add a new Application that has the MainProject property set.
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
I don't understand what the problem is. MainProject is not mandatory, in fact the insert works if I don't set that property. There is a circular dependency, but there is a clear order that works
Is there any way to tell Entity Framework to do this?
edit:
Here are the configurations:
public ApplicationConfiguration()
: base()
{
HasKey(a => a.ID);
ToTable("Applications");
HasOptional(a => a.MainProject);
}
public SolutionConfiguration()
: base()
{
ToTable("Solutions");
}
public ProjectConfiguration()
: base()
{
ToTable("Projects");
}
Upvotes: 0
Views: 3119
Reputation: 9463
You can configure this in the DbModelBuilder
using the fluent api or in the Entity Models using data annotations. Basically, you have to tell EF which Entity is the principal end and which is the dependent (think cascade delete...).
For example, if Application
is the principal and there can be 0 or 1 MainProject
, and MainProject
shall not exist without Application
, and MainProject
shall be deleted when Application
gets deleted:
ModelBuilder.Entity<Application>().HasOptional(a => a.MainProject).WithRequired().WillCascadeOnDelete(true);
Application has many Solutions, and Application is required for a valid Solution, with backlink:
ModelBuilder.Entity<Application>().HasMany(a => a.Solutions).WithRequired(s => s.Application);
Solution has many Projects, with backlink:
ModelBuilder.Entity<Solution>().HasMany(s => s.Projects).WithMany(p => p.Solutions);
See Configuring Relationships with the Fluent API
Upvotes: 0