티스토리 뷰

😀 .NET Core Blazor

SqlQuery VS ExecuteSql

James Wetzel 2024. 3. 21. 14:54

SqlQuery와 ExecuteSql의 차이점을 알아야한다.

 

 

SqlQuery

List<WordEntity> wordEntities = context.Database.SqlQuery<WordEntity>($"""
    select 
        word.WordSeq
    ,   word.Spelling
    ,   word.Meaning
    ,   word.NationSeq
    from dbo.Word as word with(nolock)
    """
).ToList<WordEntity>();

 

ExecuteSql & ExecuteSqlAsync

public long SetWord(WordEntity wordEntity)
{
    using (var context = new SQLDBContext()) 
    {
        return context.Database.ExecuteSql($"""
            insert into dbo.Word ( 
                Spelling
            ,   Meaning
            ,   NationSeq
            ) values (
                {wordEntity.Spelling}
            ,   {wordEntity.Meaning}
            ,   1
            )
            """
        );
    }
}

public async Task<long> SetWord(WordEntity wordEntity)
{
    using (var context = new SQLDBContext()) 
    {
        return await context.Database.ExecuteSqlAsync($"""
            insert into dbo.Word ( 
                Spelling
            ,   Meaning
            ,   NationSeq
            ) values (
                {wordEntity.Spelling}
            ,   {wordEntity.Meaning}
            ,   1
            )
            """
        );
    }
}

 

 

ExecuteSqlRawAsync

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

public async Task<int> SetWord(WordEntity wordEntity)
{
    using (var context = new SQLDBContext()) 
    {
        var pId = new SqlParameter("@id", SqlDbType.Int);
        pId.Direction = ParameterDirection.Output;

        string query = "insert into dbo.Word (Spelling, Meaning, NationSeq, Level) values (@p0, @p1, @p2, @p3); set @id = scope_identity();";

        await context.Database.ExecuteSqlRawAsync(query, "fff", "ddd", 1, "B2", pId);
        var id = (int)pId.Value;
        return id;
    }
}
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함