• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

ADO.NET中的DBNull

在ADO.NET和EF Core中使用DbParameter/SqlParameter时,如果要传递数据库null值给数据库必须要使用DBNull,下面的微软文档介绍了DBNull:

DBNull Class

其中这里有提到DBNull.Value.Equals方法的使用。

 

同时在下面这篇微软ADO.NET的文档中,也有提到:

When you send a null parameter value to the server, you must specify DBNull, not null (Nothing in Visual Basic). The null value in the system is an empty object that has no value. DBNull is used to represent null values.

Configuring parameters

 

下面的代码演示了,如何在EF Core和SqlParameter中使用DBNull更新数据库表中的值:

using DBNullDemo.Entities;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace DBNullDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using (DemoDbContext dbContext = new DemoDbContext())
            {
                string sql = "update [dbo].[Students] set Grade=@grade where Id=@id";
                SqlParameter gradeParameter = new SqlParameter()
                {
                    ParameterName = "grade",
                    SqlDbType = SqlDbType.NVarChar,
                    Value = DBNull.Value
                };

                SqlParameter idParameter = new SqlParameter()
                {
                    ParameterName = "id",
                    SqlDbType = SqlDbType.Int,
                    Value = 3
                };

                dbContext.Database.ExecuteSqlRaw(sql, gradeParameter, idParameter);
            }

            Console.WriteLine("Press any key to end...");
            Console.ReadLine();
        }
    }
}

 

posted @ 2024-10-28 20:23  PowerCoder  阅读(70)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3