Linq To Sql为什么我会获得重复记录?

时间:2010-04-23 14:27:57

标签: linq-to-sql duplicates

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

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;
}

1 个答案:

答案 0 :(得分:0)

我可以从您的代码中推断出user_history和action是通过外键关系链接的。

在这种情况下,尽管Linq2SQL将您的操作作为user_history中的字段,但如果您需要将新的user_history与现有操作相关联,则应返回操作的主键并在user_history对象中设置关系的相应字段

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

或者,您可以更改GetUserAction以在数据库中插入操作(如果它是新操作)。这样,您可以保证它始终返回数据库中已存在的操作。