1

I am trying to create one-to-many relation between 2 classes and mainly I am trying to set a composite key between room number and campusid. I have tried using annotations and overriding the modelbuilder, but still nothing worked...

This is the exception that throws:

Unhandled Exception: System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation: Room_Campus_Target_Room_Campus_Source: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.

Here are my models:

public class Room
{
    public int Id { get; set; }

    [StringLength(4, MinimumLength = 3)]
    public string Number { get; set; }
    public int CampusId { get; set; }
    //[ForeignKey("Number, CampusId")]
    public virtual Campus Campus { get; set; }
}

public class Campus
{
    public Campus()
    {
        this.Rooms = new HashSet<Room>();
    }
    public int Id { get; set; }
    [StringLength(4)]
    public string Number { get; set; }
    public virtual ICollection<Room> Rooms { get; set; }
}

Here is my modelbuilder attepmt with same exception..

modelBuilder.Entity<Room>()
            .HasRequired(r => r.Campus)
            .WithMany(c => c.Rooms)
            .HasForeignKey(c => new { c.Number, c.CampusId });

Thanks in advance! :)

Martin Indzhov
  • 119
  • 1
  • 5
  • There must be a list of validation errors following the above exception message. Can you post it as well? – Eduard Malakhov Apr 14 '17 at 21:18
  • Yeah, sorry I didn't see that i haven't paste it all :) – Martin Indzhov Apr 14 '17 at 22:07
  • The message is pretty self-explaining, you've got different constraints on the key property `Number`: once it is `[StringLength(4, MinimumLength = 3)]`, the other time it's `[StringLength(4)]`. They need to be strictly consistent. – Eduard Malakhov Apr 14 '17 at 22:10
  • I tried again with no constraints at all and same exception occured. – Martin Indzhov Apr 15 '17 at 09:13
  • 1
    it's quite easy really. you declare the FK from Rooms to Campus to be a tuple of two properties, int and string. However, the PK of Campus only consists of one property, Id. Declare the key of campus to be Id+number, and you should be set. – DevilSuichiro Apr 15 '17 at 12:25

0 Answers0