user342552
user342552

Reputation:

One to many relationship error

I have the following model, but I keep getting an error:

Unhandled Exception: System.InvalidOperationException: A relationship multiplici ty constraint violation occurred: An EntityReference can have no more than one r elated object, but the query returned more than one related object. This is a no n-recoverable error.

 public class Tournament
    {
        public long TournamentId { get; set; }        
        public string Title { get; set; }        
        public virtual User CreatedBy { get; set; }                    
    }

 public class User
    {
        public int UserId { get; set; }

    }

        modelBuilder.Entity<Tournament>()
            .HasRequired(t => t.CreatedBy)
            .WithOptional()               
            .Map(c => c.MapKey("CreatedById")); // correct column name

Upvotes: 1

Views: 4586

Answers (3)

Krptodr
Krptodr

Reputation: 139

This can also happen if you have lazy loading enabled and not specifying all the navigation properties as Overridable (C# Virtual).

Upvotes: 0

DDiVita
DDiVita

Reputation: 4265

You'll have better luck managing Foreign keys if you modify you model a bit:

public class Tournament
    {
        public long TournamentId { get; set; }        
        public string Title { get; set; } 
        public virtual int CreatedById {get;set;}       
        public virtual User CreatedBy { get; set; }                    
    }

and your mapping would look more like this:

modelBuilder.Entity<Tournament>()
        .HasRequired(t => t.CreatedBy)
        .WithMany()               
        .HasForeignKey(t => t.CreatedById); // correct column name

This way, when you create a new Tournament Entity you need only pass in the CreatedById and not the entire User object.

Upvotes: 0

Eranga
Eranga

Reputation: 32447

Your model fluent configuration entry is incorrect. Change it as follows

    modelBuilder.Entity<Tournament>()
        .HasRequired(t => t.CreatedBy)
        .WithMany()               
        .Map(c => c.MapKey("CreatedById")); // correct column name

Upvotes: 5

Related Questions