Entity Framework 4.1 doesn't put data into database on SaveChanges()
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 ta开发者_运维知识库g 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?
Several things things. One, you are doing it wrong:
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.
Databases are capable of checking such constraints, so use the database, not the code.
Second thing -- your code is not only inefficent (you hit db twice) but buggy too. You check the name against the database, let's say it does not exist, so you add a tag, then you check the same name, it still does not exists, so you add it again!
You save it, and then you cannot get single record, because you just saved 2 records of the same name.
精彩评论