I have table inheritance in database:
Ticket{TicketId, TicketTypeId, CreatedBy, Title, Description etc.}
UserInfo{TicketId etc.}
TicketId is primary key auto increment. Table UserInfo inherit Ticket table so TicketId in UserInfo is actualy FK for TicketId from Ticket table.
I have model in EF:
public abstract class Ticket
{
[Key]
public int TicketId { get; set; }
public int TicketTypeId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Guid CreatedBy { get; set; }
public virtual User User { get; set; }
}
public class UserInfo :Ticket
{
...
}
When I try to insert new UserInfo object to database I write:
User u = context.Users.Find(Membership.GetUser().ProviderUserKey);
UserInfo o = new UserInfo();
o.CreatedBy = u.UserId;
o.Description = "First EF user info to database!";
o.TicketTypeId = 1;
o.Title = "First User Info EF";
context.Tickets.Add(o);
context.SaveChanges();
But application break on SaveChanges().
I get the following error:
{“Invalid column name ‘User_UserId’.”}
UPDATE
I changed CreatedBy to UserId and I pass this error, but now I have two more issues here:
I save UserInfo to database but there is nothing in UserInfo table. I thought that EF can add this field after save?
This ticket table in database is bound to UserInfo but it’s also bounded to few more tables in database by TicketID but when I try to save object UserInfo I get this error:
{"The INSERT statement conflicted with the FOREIGN KEY
constraint \"FK_Tickets_Groups\". The conflict occurred in database \"db_Example\", table \"dbo.Groups\", column 'TicketId'.\r\nThe statement has been terminated."}
So to save this I currently removed table references except UserInfo. Can EF handle this situation?
It’s not necessary to change the property name. You just need to tell EF that
CreatedByis the foreign key for theUserproperty (EF doesn’t detect this automatically because the name doesn’t follow the naming conventions):If you have the derived entity properties in a separate table you must specify the table name for this entity (Table-Per-Type (TPT) inheritance mapping), otherwise EF will put all derived entities into the same table as the base entity by default (Table-Per-Hierarchy (TPH) inheritance mapping):
It seems that
TicketorUserInfohas a foreign key to a tableGroupsand that this foreign key property is not set to valid group key value. When you insert the entity the foreign key constraint in the database is violated which results in the exception.