Green Falcon
Green Falcon

Reputation: 836

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, a word column. 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 fine but when I add a value which already exists in the table, calling this.context.SaveChanges(); in the AddSynonymDA method, always throws an exception which was for the previous first exception which caused the first exception and nothing is added to database even if they do not exist in the database. Why is that?

I get the following error which shows that Java already exists. The problem is that Java is 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."}

Upvotes: 0

Views: 184

Answers (2)

user3447394
user3447394

Reputation:

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 .

Upvotes: 1

The Net Master
The Net Master

Reputation: 146

I suspect that you have not set a column to be an Identity column in your database

In other words when you are inserting an entity you need a column to be automatically incrementing. The way I do this is for example using SQL server:

ALTER TABLE [User] DROP COLUMN [ID];

ALTER TABLE [User] 
    ADD [ID] integer identity not null;

If you do not have an ID column already you do not need the first line. After this, update your EF model in your project by deleting the User table and right clicking and Updating Model from Database and select the table.

So now when you insert new entries in you EF model, the ID column will be automatically incremented and you won't get an error.

Upvotes: 1

Related Questions