1

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?

4

1 に答える 1

1

CreatedBy を UserId に変更し、このエラーを渡しました...

プロパティ名を変更する必要はありません。CreatedByプロパティの外部キーであることを EF に伝える必要があるだけですUser(名前が命名規則に従っていないため、EF はこれを自動的に検出しません)。

[ForeignKey("User")]
public Guid CreatedBy { get; set; }
public virtual User User { get; set; }

UserInfo をデータベースに保存しましたが、UserInfo テーブルには何もありません。EFは保存後にこのフィールドを追加できると思いましたか?

別のテーブルに派生エンティティ プロパティがある場合は、このエンティティのテーブル名を指定する必要があります ( Table-Per-Type (TPT)継承マッピング)。それ以外の場合、EF はすべての派生エンティティを既定で基本エンティティと同じテーブルに配置します。 ( Table-Per-Hierarchy (TPH)継承マッピング):

[Table("UserInfo")]
public class UserInfo : Ticket
{
    ...
}

...このエラーが表示されます...

TicketまたはUserInfoテーブルへの外部キーがGroupsあり、この外部キー プロパティが有効なグループ キー値に設定されていないようです。エンティティを挿入すると、データベースの外部キー制約に違反し、例外が発生します。

于 2012-06-03T12:48:03.607 に答える