Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linq to sql Linq To Sql为什么我会得到重复的记录?_Linq To Sql_Duplicates - Fatal编程技术网

Linq to sql Linq To Sql为什么我会得到重复的记录?

Linq to sql Linq To Sql为什么我会得到重复的记录?,linq-to-sql,duplicates,Linq To Sql,Duplicates,在下面的代码中,GetUserAction确实返回一个action实例,但是当用户实例提交到数据库时,它会在数据库中创建一个额外的action行,而不是创建与返回的现有行的关系?为什么? using (UserRepository repository = new UserRepository()) { var user = new user { user_created = DateTime.Now, user_email = email,

在下面的代码中,GetUserAction确实返回一个action实例,但是当用户实例提交到数据库时,它会在数据库中创建一个额外的action行,而不是创建与返回的现有行的关系?为什么?

using (UserRepository repository = new UserRepository())
{
    var user = new user
    {
        user_created = DateTime.Now,
        user_email = email,
        user_password = GetHashedPassword(password)                            
    };

    // create an entry in the users history
    user.user_histories.Add(new user_history
    {
        user_history_date = DateTime.Now,
        action = GetUserAction("Registered")
    });                          

    // commit the new user to the database
    repository.InsertUser(user);
    repository.Save(); 
}

public static action GetUserAction(string userAction)
{
    action a = null;

    using (UserRepository repository = new UserRepository())
    {
        a = repository.SelectUserAction(userAction);

        // in the SO example I know a is not null so ignore the next 8 lines
        if (a == null)
        {
            a = new action
            {
                action_name = userAction
            };                    
        }
   }

   return a;
}

我可以从您的代码推断,用户历史和操作是通过外键关系链接的

在这种情况下,尽管Linq2SQL将操作作为用户_历史记录中的字段提供,但如果需要将新用户_历史记录与现有操作链接,则应返回操作的主键,并在用户_历史记录对象中设置关系的相应字段

编辑:如果操作的主键是标识自动生成的列,则可以通过将其与零进行比较来检查该列是否为新列。新对象的id设置为零


或者,如果操作是新的,您也可以修改GetUserAction以在数据库中插入该操作。这样,您可以保证它总是返回数据库中已经存在的操作。

如果您在保存用户的同一上下文中检索用户操作,会发生什么情况?@Gregoire我尝试过,效果很好,这没问题,但我想将UserAction retrieval提取到一个单独的方法中,在这种情况下@Daniel C.S.如果我能确定返回的操作是新的还是现有的,那么answer就会起作用。我可以看出这会起作用,尽管我不明白为什么隐藏在幕后,但是我无法从调用方法中确定返回的操作是否为新操作。我可以返回一个包含bool for new或not加上action的对象,但这似乎是错误的