我真的很喜歡我的日期時間在我的休息服務。我想要的是創建一個新的日期如下:由於外鍵不能將datetime2保存在數據庫中?
Date ter = new Date()
{
StartTime = dto.StartTime,
EndTime = dto.EndTime,
Name = dto.Name,
Place = dto.Place,
Datetype = tera,
Type = dto.Type,
//Squad = new Squad(),
TeamNumber = mannschaft.Id
};
uow.RepDate.Create(ter);
//mannschaft.Dates.Add(ter);
uow.SaveChanges();
而不是創建這個日期我收到此錯誤信息:
同時節省不暴露於外鍵的屬性的實體時出錯他們的關係。 EntityEntries屬性將返回null,因爲單個實體不能被識別爲異常的來源。通過在您的實體類型中公開外鍵屬性,可以更輕鬆地處理保存時的異常。有關詳細信息,請參閱InnerException。
我沒有在我的日期實體中設置任何外鍵。發生了什麼?
編輯
我的約會實體:
public class Date
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Place { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
//public Squad Squad { get; set; }
public virtual Datetype Datetype { get; set; }
[ForeignKey("Datetype")]
public int DatetypeId { get; set; }
public string Type { get; set; }
public virtual ICollection<Participation> Participations { get; set; }
public virtual Squad Squad { get; set; }
public int TeamNumber { get; set; }
}
現在(日期實體改變字段)
內部異常:
INSERT語句衝突與外鍵約束\」 FK_dbo.Dates_dbo.Datetypes_DatetypeId \」。衝突發生在數據庫\「SchoolDb \」,表\「dbo.Datetypes \」,'DatetypeId'列中。\ r \ n該語句已被終止。
Datetype:
public class Datetype
{
[Key]
public int DatetypeId { get; set; }
public string Name { get; set; }
//public virtual ICollection<Squad> Squads { get; set; }
public int TeamId { get; set; }
}
編輯 的問題是在這裏,我想:
Datetype tera=new Datetype();
if (mannschaft != null)
{
if (!dto.DatetypeId.Equals(null)) {
foreach (Datetype termin in mannschaft.Datetypes)
{
if (termin.DatetypeId == dto.DatetypeId)
{
tera = termin;
}
}
每當我測試的服務,我是懶得去創建一個Datetype的日期,以便泰拉是一個空的日期類型。所以外鍵有幾個問題可以找到日期類型。當我創建一個日期類型時,一切正常。有沒有辦法讓datetype可選?
你能給你的數據庫結構的更多信息嗎?例如。實體框架設計器的屏幕截圖。 – Simon
'datetime2'與錯誤有什麼關係?錯誤提示您的Date實體被配置爲與其他一些類沒有實際指定要使用的鍵的關係。由於您沒有提供'日期'的定義或上下文配置 –
,因此無法猜測哪個關係,請向我們提供您的Date類和它的映射。我們無法調試所有向我們展示的值的代碼是將一個值分配給另一個值,然後調用'SaveChanges' –