简体   繁体   中英

Many-to-one relationship

I have a schema Definitions which I would like to be able to reference itself. As I need meta data about the reference, there's a coupling schema named Associations . I'm using Entity Framework's fluent API in conjunction with data annotation attributes.

Definitions:

public class Definition
{
    [Key]
    public int Id { get; set; }
    // ...
    public virtual ICollection<Association> Associations { get; set; }
}

Associations:

public class Association
{
    [Key]
    public int Id { get; set; }
    public int TypeId { get; set; }
    public int AssociatedDefinitionId { get; set; }
    public int RootDefinitionId { get; set; }

    public virtual AssociationType Type { get; set; }
    public virtual Definition AssociatedDefinition { get; set; }
    public virtual Definition RootDefinition { get; set; }
}

OnModelCreating:

modelBuilder.Entity<Association>()
    .HasRequired(p => p.AssociatedDefinition)
    .WithRequiredPrincipal();

modelBuilder.Entity<Association>()
    .HasRequired(p => p.RootDefinition)
    .WithRequiredPrincipal();

I use MySQL as the database engine. When I try to save a definition entity with an empty association collection, I get a constraint violation:

Cannot add or update a child row: a foreign key constraint fails ("u0228621_8"."Definitions", CONSTRAINT "FK_Definitions_Associations_Id" FOREIGN KEY ("Id") REFERENCES "Associations" ("Id"))

What am I doing wrong?

You have defined your association class with all relationships being "required:required" because of the WithRequiredPrincipal which doesn't seem to be what you want. Since the Associations collection appears (from the comments) to be the relation from the Root definitions, the mapping should come from definition, like so:

// Foreign key mappings included.
modelBuilder.Entity<Definition>().HasMany(d => d.Assocations)
  .WithRequired(a => a.RootDefinition).HasForeignKey(a => a.RootDefinitionId);
modelBuilder.Entity<Association>().HasRequired(a => a.AssociatedDefinition)
  .HasForeignKey(a => a.AssociatedDefinitionId);

So the Associations collection may be empty, but every Association requires a RootDefinition and AssociatedDefinition .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM