温馨提示:本文翻译自stackoverflow.com,查看原文请点击:entity framework - What is the best way to insert if not exist, otherwise update in entityframework core?
entity-framework entity-framework-core

entity framework - 如果不存在,最好在 Entity framework 核心中进行更新的最佳方式是什么?

发布于 2020-04-08 12:27:58

这是模型:

public class UserModel
{
        public boolean Online{ get; set; }        
        [Key]
        public string id { get; set; }

}

这是DBContext:

 public class UserDBContext:DbContext
 {
        public virtual DbSet<UserModel> UserStatus { get; set; }
        public UserDBContext(DbContextOptions options) : base(options)
        {

        }

        protected UserDBContext()
        {
        }
}

当用户在线时,需要将其状态记录到数据库中。

如果id数据库中不存在,则将其插入。

如果id数据库中存在,请对其进行更新。

现在我这样做:

public async Task SetUserStatus(UserModel UM)
{

    if (UserDBContext.UserStatus.Where(X => X.id == UM.id).Count() != 0)
    {
       UserDBContext.UserStatus.Update(UM);
    }
    else
    {
       UserDBContext.UserStatus.Add(UM);
    }
    UserDBContext.SaveChanges();                      
}

尽管它可以工作,但我担心有数百万个数据时的性能。数据库将计算所有数据,而我只需要一个。

我该如何解决?谢谢。

查看更多

提问者
Melon NG
被浏览
62
Phong 2020-02-01 11:34

您应该Any()改用

确定序列中的任何元素是否存在或满足条件。

if (UserDBContext.UserStatus.Any(X => X.id == UM.id))
{
   UserDBContext.UserStatus.Update(UM);
}