I have a problem when using the new Entity Framework 4.1. I started testing it a few days ago, and I am still new to the whole POCO concept and this new API.
Anyway, while doing some coding I created something like this:
public Tag GetTagWithName(string name)
{
if (db.Tags.SingleOrDefault(q => q.Name == name) == null)
{
return new Tag { Name = name };
}
else
{
return db.Tags.SingleOrDefault(q => q.Name == name);
}
}
Which is supposed to check in the database if the Tag this such a name already exists, and I am using this function in this piece of code:
if (tags != null)
{
foreach (HtmlNode tagNode in tags)
{
string tagString = tagNode.InnerText.Remove(0, 1);
Tag tag = TagRep.GetTagWithName(tagString);
pic.Tags.Add(tag);
}
}
if (context.Pictures.Any(q => q.Link == pic.Link))
{
continue;
}
else
{
context.Pictures.Add(pic);
}
context.SaveChanges();
Which is basically adding Tags to newly created photos, check if the photo is in database already and than if not add it to database, and invoke SaveChanges() after every picture.
Well my problem it, that during execution function GetTagWithName causes an error "Sequence contains more than one element" on getting "SingleOrDefault", which shouldn't happen, because I check the whole database before adding any new tag, using this function to check if the tag is already in DB.
From what I saw in my code, the situation happens because of the fact, that even if I add to the Picture a Tag object which I took from database, it still later on adds it as a new object to the Tags table.
Is there any explaination for that?
contextvariable into theGetTagWithNamemethod and using it instead of thedbvariable. See if this fixes your problem.