简体   繁体   中英

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."}

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.

您最初必须检查该项目是否存在,因为您似乎有一个唯一的约束,然后应在代码中使用reference的属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM