我使用MVC實體框架使票務系統5INSERT語句衝突與外鍵
如何我的類映射:
用戶管理員爲1〜0..1(我可以某些用戶分配與管理狀態,但我不希望每個用戶都擁有它)
管理員票是1比1(只能分配1名管理員(解決問題),以一票)
用戶到票證是1到很多(一個用戶可以創建多張票)
我遇到這個問題:如果我創建一個用戶有一張票,不具有adminID(看看here)這會給我下面的錯誤:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Ticket_dbo.Administrator_UserID". The conflict occurred in database "RecreationalServicesTicketingSystem.DAL.IssueContext", table "dbo.Administrator", column 'UserID'. The statement has been terminated.
我覺得問題是因爲「Admin to Tickets」之間的映射。 1對1關係強制條件,如果我創建票證,用戶必須具有「adminID」或數據庫中存在衝突。
我的問題是,什麼映射應Admin到Tickets是爲了解決這個問題? 也許1到0 .. *(1對1或很多)它會解決這個問題嗎?
管理員
public class Administrator
{
[ForeignKey("User")]
public int UserID { get; set; }
[StringLength(50)]
public virtual User User { get; set; }
[Key]
*public int AdminID { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }*
}
Ticket.cs
public enum Priority
{
Low, Med, High
}
public class Ticket
{
public int TicketID { get; set; }
public string Issue { get; set; }
[DisplayFormat(NullDisplayText = "No Priority")]
public Priority? Priority { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public int CategoryID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
public int UserID { get; set; }
*public int AdminID { get; set; }*
}
應用安迪的解決方案,我做管理員票1:許多關係 (在Ticket.cs新增public virtual Administrator Administrator { get; set; }
)
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Ticket_dbo.Administrator_UserID". The conflict occurred in database "RecreationalServicesTicketingSystem.DAL.IssueContext", table "dbo.Administrator", column 'UserID'. The statement has been terminated.
管理員
public class Administrator
{
[ForeignKey("User")]
public int UserID { get; set; }
[StringLength(50)]
public virtual User User { get; set; }
[Key]
*public int AdminID { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }*
}
public class Ticket
{
public int TicketID { get; set; }
public string Issue { get; set; }
[DisplayFormat(NullDisplayText = "No Priority")]
public Priority? Priority { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public int CategoryID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
public int UserID { get; set; }
*public int AdminID { get; set; }
public virtual Administrator Administrator { get; set; }*
}
門票管理員1:1 - 只有一個管理員可以在門票上工作,管理員以門票1:很多 - 管理員可以分配給多張門票。 – Kevin
有人建議我讓adminID爲空int'int?'。它會有同樣的效果嗎? – TykiMikk