我如何使用 SaveChanges() 来保存现有数据?

How can i use SaveChanges() in order to save existing data?

我只需要更改一些已经保存在 SQL 数据库中的数据。

这是我的代码:

var userData = new MinciUsers
{
    ApplicationUserId = stringUserId,
    Name = userUnity.firstName,
    LastName = userUnity.lastName,
    DateOfBirth = date,
    Address = userUnity.address,
    CityId = null,
    CountryId = null,
    LanguageId = null,
};

dbContext.MinciUsers.Add(userData);
dbContext.SaveData();

当我更改一些数据时,它会抛出错误,因为主键已经存在。

更改数据时如何使用SaveChanges()

一种方法是首先从数据库中获取相应的对象,然后通过指定新值来更改其状态。最后你在相应的上下文 class 上调用 SaveChanges 来保存更改。

例如,如果主键在您的应用程序中表示为 Id:

var minciUser = dbContext.MinciUsers.SingleOrDefault(m => m.Id == 1);
if(minciUser != null)
{
    // The record with Id 1 has been found. So you can change it's state.

    minciUser.ApplicationUserId = stringUserId;

    // here you will add the rest of the fields you want to update.       

    dbContext.SaveChagnes();
}

更新

另一种方法 ii 是利用 AddOrUpdate:

var userData = new MinciUsers
{
    ApplicationUserId = stringUserId,
    Name = userUnity.firstName,
    LastName = userUnity.lastName,
    DateOfBirth = date,
    Address = userUnity.address,
    CityId = null,
    CountryId = null,
    LanguageId = null,
};

dbContext.MinciUsers.AddOrUpdate(userData);
dbContext.SaveChanges();