ADO.NET中的DBNull
在ADO.NET和EF Core中使用DbParameter/SqlParameter时,如果要传递数据库null值给数据库必须要使用DBNull,下面的微软文档介绍了DBNull:
其中这里有提到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.
下面的代码演示了,如何在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(); } } }