简体   繁体   中英

EF Core FromSQLRaw and Stored Procedures to insert data

I have a Entity Framework Core application. I have a stored procedure which I use to insert data. The stored procedure is used elsewhere so I cannot change it.

When I call it to create an entry, it does not work because the Description column is not returned from the stored procedure. So I get an error when I call FromSQLRaw unless I set Description as [NotMapped] .

However, I don't want to use [NotMapped] because I might do something like

dm.Offices.Where(o => o.Id > 10)

and surely [NotMapped] will not return unmapped columns. So what can I do?

using (var dm = new DatabaseModel())
{
    Office london = new Office { Description = "london" };
    var item = dm.Offices.FromSqlRaw("EXECUTE sp_addoffice {0}", london.Description);
}
public partial class Office
{
    [Key, Column("OfficeID")]
    public int ID { get; set; }
    public string Description { get; set; }
}

public partial class DatabaseModel : DbContext
{
    public virtual DbSet<Office> Offices { get; set; }
}
CREATE TABLE [dbo].[Offices]
(
    [OfficeID] [int] IDENTITY(1,1) NOT NULL primary key,
    [Description] [varchar](50) NULL
)

CREATE PROCEDURE [dbo].[sp_addoffice]
    @Description varchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO offices (Description) 
    VALUES (@Description)

    SELECT SCOPE_IDENTITY() AS OfficeID
END

Create new class

public class OfficeId
{
public int Id {get; set;}
}

Add this class to you EF context:

public virtual DbSet<OfficeId> OfficeIds { get; set; }

   modelBuilder.Entity<OfficeId>(e =>
            {
                e.HasNoKey();
            });

After this use just this:

 var officeId = dm.OfficeIds.FromSqlRaw("EXECUTE sp_addoffice {0}", london.Description);

After this you can use this you can validate an officeId.Id and use any way you are needed.

You could change the SQL to something that returns the proper shape after running the stored procedure. EG:

set nocount on;
declare @ids table(id int);

insert into @ids(id)
execute sp_addoffice {0};

select *
from offices 
where id = ( select top 1 id from @ids );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM