C4p741nZ C4p741nZ - 1 month ago 10
C# Question

EF junction table with additional Id throws exception on save

This question is related to my Original Question.

I got it to work which is nice but a few secs ago I noticed that it's not 100% what I expected.

public class Entry{
public IEnumerable<EntryHardware> RequestedHardware {get; set;}
}

public class EntryHardware{
[Key]
[Column(Order=0)]
public int EntryId {get; set;}
[Key]
[Column(Order=1)]
public int HardwareId {get; set;}
public AdditionalProperty Foo {get; set;}
}

public class Hardware{
public string Name {get; set;}
}


using this approach a Entry can contain n different Hardware but adding the same Hardware twice will result in a not unique Id-Set.

To solve this I added a new unique Property to my EntryHardware Model:

public class EntryHardware{
[Key]
[Column(Order=0)]
public int Id {get; set;}
[Key]
[Column(Order=1)]
public int EntryId {get; set;}
[Key]
[Column(Order=2)]
public int HardwareId {get; set;}
public AdditionalProperty Foo {get; set;}
public virtual Entry ...
public virtual Hardware ...
}


Unfortunately this way the Id Property won't get set automatically through the DB. Looking for an answer I found an attribute which should solve this:

public class EntryHardware{
[Key]
[Column(Order=0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get; set;}
[Key]
[Column(Order=1)]
public int EntryId {get; set;}
[Key]
[Column(Order=2)]
public int HardwareId {get; set;}
public AdditionalProperty Foo {get; set;}
public virtual Entry ...
public virtual Hardware ...
}


But using this my code throwns an exception when it comes to saving the Entities to the DB:


Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.


but I can't figure out where the problem lies here....

Answer

[Promoted from a comment]

Stop and take a step back.... What are you trying to achieve?

Why not just give the join table its own (meaningless) ID, make the Hardware/Entry ids foreign keys and call it a day?

Bear in mind that the Key attribute is only required on fields used to identify records in that specific table (the primary key for the table). Using the attribute on multiple fields creates a composite key (and this is where your unique constraint is coming from).