参数少于关联对象的存储过程

本文关键字:对象 存储过程 关联 于关联 参数 | 更新日期: 2023-09-27 18:31:12

我的数据库中有一个存储过程(sp_create_user),它在我的Users表中创建一个用户。这是我的存储过程定义:

ALTER PROCEDURE sp_create_user
    @Username nvarchar(50),
    @Password nvarchar(50),
AS
BEGIN
    -- SQL STATMENTS
END

我在 c# 中的User对象是这样的:

public partial class User
{
    public User()
    {
    }
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

这是我将用户实体插入映射到该存储过程的 EF:

modelBuilder.Entity<User>().MapToStoredProcedures(
  s =>
      s.Insert(i => i.HasName("sp_create_user"))
);

当我尝试执行用户的新创建时,我收到一个异常,即发送到存储过程的参数数量太大。跟踪查询后,我看到它将User类具有的所有字段发送到存储过程。

如何告诉 EF 仅发送存储过程的相关字段?

参数少于关联对象的存储过程

...
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public string FirstName { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public string LastName { get; set; }
...

如果您不想修改类,也可以尝试以下操作:

modelBuilder.Entity<User>().Ignore(u => u.UserId);