[英]An object with the same key already exists in the ObjectStateManager. when using AsNoTracking
[英]LINQ Initializer Throws a “An object with the same key already exists in the ObjectStateManager.”
DataLayer.Image image = new DataLayer.Image();
image.DateCreated = DateTime.Now;
image.ImageData = (byte[])Session[STR_UploadedImage];
image.TimeStamp = imageDateTimeUserControl.DateTime;
image.Incident_Id = int.Parse(Request.QueryString[STR_IncidentId]);
image.CreatedBy_Id = db.Employees.First(em => em.Username == Context.User.Identity.Name).Id;
db.Images.AddObject(image);
foreach (NumericTag tag in tags.OfType<NumericTag>())
{
var numericTags = db.Tags.OfType<NumericTag>().Where(t => t.TagType.Id == tag.TagType.Id && t.Value == tag.Value);
image.Tags.Add(numericTags.Any() ? numericTags.First() : new NumericTag
{
TagType = tag.TagType,
Value = tag.Value
});
}
foreach (TextualTag tag in tags.OfType<TextualTag>())
{
var textualTags = db.Tags.OfType<TextualTag>().Where(t => t.TagType.Id == tag.TagType.Id && t.Description == tag.Description);
image.Tags.Add(textualTags.Any() ? textualTags.First() : new TextualTag
{
TagType = tag.TagType,
Description = tag.Description
});
}
db.SaveChanges();
detailsPanel.Visible = false;
imagePanel.Visible = false;
uploadPanel.Visible = true;
我正在嘗試將屬性(標簽)添加到圖像,因為它已添加到數據庫中。 我在ViewState中存儲了一個臨時標簽列表。 當行image.Tags.Add
嘗試添加現有標簽時,它可以正常工作,但是當它執行初始化程序時,它將引發“ ObjectStateManager中已經存在具有相同鍵的對象”。 例外。
有人看到我在做什么錯嗎?
但是從另一個頁面向數據庫中現有圖像添加標簽的此方法可以正常工作:
TagType tagType = tagTypes[tagTypeDropDownList.SelectedIndex];
int numericTagValue;
if (tagType is NumericTagType & !int.TryParse(tagDecriptionTextBox.Text, out numericTagValue))
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "TagError",
string.Format("alert('Only numeric values are valid for tags of type {0}.');", tagType.Name), true);
return;
}
foreach (var imageId in imageCheckBoxList.Items.Cast<ListItem>().Where(i => i.Selected)
.Select(i => int.Parse(i.Value)))
{
var image = db.Images.First(i => i.Id == imageId);
var tags = db.Tags.AsEnumerable().Where(t => t.TagType.Id == tagType.Id
&& (t is TextualTag ?
((TextualTag)t).Description == tagDecriptionTextBox.Text :
((NumericTag)t).Value == numericTagValue));
if (tags.Any())
{
var tag = tags.First();
if (!image.Tags.Select(t => t.Id).Contains(tag.Id))
image.Tags.Add(tag);
}
else
{
if (tagType is NumericTagType)
image.Tags.Add(new NumericTag
{
TagType = (NumericTagType)tagType,
Value = numericTagValue
});
else
image.Tags.Add(new TextualTag
{
TagType = (TextualTagType)tagType,
Description = tagDecriptionTextBox.Text
});
}
db.SaveChanges();
}
attributeListView.DataBind();
tagDecriptionTextBox.Text = "";
這個說法:
new TextualTag
{
TagType = tag.TagType,
Description = tag.Description
});
不授予對象唯一性。 您必須為新標簽指定主鍵。
如果您正在使用Guids
,這很簡單。 Guid.NewGuid()
解決了所有問題。
如果將int
與Identity
一起使用,則需要使用另一個屬性使對象彼此不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.