[英]The relationship could not be changed because one or more of the foreign-key properties is non-nullable. (2)
[英]he relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship
錯誤信息:
操作失敗:由於一個或多個外鍵屬性不可為空,因此無法更改該關系。 對關系進行更改時,相關的外鍵屬性將設置為空值。 如果外鍵不支持空值,則必須定義新的關系,必須為外鍵屬性分配另一個非空值,或者必須刪除不相關的對象。
我的代碼:
foreach (StakeholderApplication stApp in stApplications)
{
StakeholderOutboundDocumentModel currentstake = outboundDocumentModels.Models.FirstOrDefault(u => u.StakeholderApplicationId == stApp.Id);
if (currentstake != null)
{
Dictionary<string, MemoryStream> Attachments = new Dictionary<string, MemoryStream>();
bool hasDocuments = false;
foreach (OutDocuments docModel in currentstake.OutDocuments)
{
if (!stApp.StakeholderOutDocuments.Any(t => t.OutDocumentId == docModel.OutDocumentId))
{
var result = await _service.DownloadBlob(allOutDocuments.FirstOrDefault(u => u.Id == docModel.OutDocumentId).Filename);
Attachments.Add(result.BlobFileName, result.BlobStream);
StakeholderOutDocument stakeholderOutDocument = new StakeholderOutDocument();
stakeholderOutDocument.OutDocumentId = docModel.OutDocumentId;
stakeholderOutDocument.Comment = docModel.Comment;
stakeholderOutDocument.StakeholderApplicationId = stApp.Id;
stApp.StakeholderOutDocuments.Add(stakeholderOutDocument);
hasDocuments = true;
}
}
if (!hasDocuments) continue;
db.Entry(stApp).State = EntityState.Modified;
}
}
db.SaveChangesAsync();
該StakeholderApplication
包含列表StakeholderOutDocuments
。
我正在嘗試將StakeholderOutDocument
對象添加到StakeholderApplication
對象中。
模型:
public partial class StakeholderOutDocument
{
public int Id { get; set; }
public int StakeholderApplicationId { get; set; }
public int OutDocumentId { get; set; }
public string Comment { get; set; }
public virtual OutDocument OutDocument { get; set; }
public virtual StakeholderApplication StakeholderApplication { get; set; }
}
利益相關者應用模型:
public partial class StakeholderApplication
{
public int Id { get; set; }
public virtual ICollection<StakeholderOutDocument> StakeholderOutDocuments { get; set; }
}
將所有單個StakeholderOutDocument
添加到StakeholderApplication
,我將StakeholderApplication
對象添加為修改后的對象,並調用db.SaveChanges
。 在出現錯誤時。
我不確定為什么會發生錯誤。 我究竟做錯了什么?
我已解決此問題。經過大量搜索。 我能夠發現要添加的對象已移至列表。 並對其進行了保存操作。.刪除了ToList並開始工作。
我不是專家。 但是我認為ToList已經從dbContext中分離了數據。 換句話說,數據將數據移入內存,因此保存的EF將其視為新條目,並嘗試更新舊條目,從而導致外鍵變為空
http://www.codeproject.com/Articles/576393/Solutionplusto-aplus-Theplusoperationplus失敗
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.