media media - 13 days ago 6
C# Question

Unusual behavior of Entity Framework

I have the following code in C#


public int AddSynonymBL(String[] syns, String word, User user)
{
int dismissedCounter = 0;
foreach (var item in syns)
{
BusinessLayerStatus.StatusBL res = this.dataAccess.AddSynonymDA(item.Trim().ToLowerInvariant(), word.Trim().ToLowerInvariant(), user);
if (res == BusinessLayerStatus.StatusBL.SynonymNotAdded)
++dismissedCounter;
}
int numberOfFailures = dismissedCounter;
return numberOfFailures;
}


And the following code is for
AddSynonymDA
method:


internal BusinessLayerStatus.StatusBL AddSynonymDA(string synonym, string word, User user)
{
try
{
Synonym newSyn = new Synonym()
{
Meaning = synonym
};
//The following if means that the searched word does not exist int the Searched table
if (this.context.Users.Where(a => a.Mail.Equals(user.Mail)).FirstOrDefault().Searcheds.Where(b => b.RealWord.Equals(word)).Count() == validNumberForKeyValues)
{
this.context.Users.Where(a => a.Mail.Equals(user.Mail)).FirstOrDefault().Searcheds.Where(b => b.RealWord.Equals(word)).FirstOrDefault().Synonyms.Add(newSyn);
this.context.SaveChanges();
return BusinessLayerStatus.StatusBL.SynonymAdded;
}
else
return BusinessLayerStatus.StatusBL.SynonymNotAdded;
}
catch (Exception ex)
{
ExceptionAction(ex);
return BusinessLayerStatus.StatusBL.SynonymNotAdded;
}
}


I am using entity framework. I have a table which contains an Id, an a word column which both of them together have unique key constraint in the database. My
main
code is as follows:


public static void Main()
{
EngineEntities context = new EngineEntities();
BusinessLogic bl = new BusinessLogic();
String[] s = new String[] { "java", "DB" };
Console.WriteLine(bl.AddSynonymBL(s, "Java", new User() { Mail = "media" }));
}


When I add a value which does not exist in the table everything is OK but when I add a value which already exists in the table facing to
this.context.SaveChanges();
in the
AddSynonymDA
method, it always throws an exception which was for the previous first exception which caused the first exception and nothing will be added to database even if they do not exist in the database. I do not know, Is there anything about Entity Framework that I have not cared about or ...?

I also have to mention that I get the following error which shows that
java
already exists, but the problem is that
java
was for the first call, as the second call I have passed
DB
not
java
.


{"Violation of UNIQUE KEY constraint 'IX_Searched'. Cannot insert duplicate key in object 'dbo.Searched'. The duplicate key value is (java, 2).\r\nThe statement has been terminated."}

Answer

you must initially check whether the item exists or not, since you seem to have a unique constraint, then you should utilize the attributes of reference in your code .