使用Entity Framework Core执行Raw sql

时间:2019-12-09 20:47:34

标签: entity-framework asp.net-core entity-framework-core

下面,我可以有一个条件来执行视图/表,该条件将加载到AccountDataModel类中。

class initialclass:
        def __init__(self):
                self.attr1 = 'one'
                self.attr2 = 'two'
class inheritedclass(initialclass):
        def __init__(self):
                super().__init__()
                self.attr3 = 'three'
        def somemethod(self):
                print (self.attr1, self.attr2, self.attr3)
a=inheritedclass()
a.somemethod()

 1. List item

如果我只想检索1或2列,该如何不使用类模型进行检索

示例:从id = 123的帐户中选择姓名

我是否总是需要一个类模型?

3 个答案:

答案 0 :(得分:0)

是的。像这样:

var account = dbcontext.AccountDataModel.FromSql(@"select a.id, a.name from account a where a.id=123");

源:FromSql for non entity type

答案 1 :(得分:0)

这查询数据库

 var name = dbcontext.GetDBConnection().Query("select name from account where id=123").FirstOrDefault();

答案 2 :(得分:0)

ADO.NET可在EFCore =中使用

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

    public void ExampleMethod(DbContext context)
    {
        SomeObjectResult result = null;
        DbCommand cmd = context.Database.GetDbConnection().CreateCommand();
        cmd.CommandText = "Select C.ID, C.CarModelID as ModelID, C.VIN, C.RegNumber,cast(C.CountValue as int) as Course,A.BrandID from   A inner join C on A.ID = C.KeyID  Where A.ID = @appID";
        cmd.Parameters.Add(new SqlParameter("@appID", appointmentID));
        if (cmd.Connection.State != ConnectionState.Open)
        {
            cmd.Connection.Open();
        }
        using (var reader = await cmd.ExecuteReaderAsync())
        {
            if (reader.Read())
            {
                result = new SomeObjectResult()
                {
                    BrandID = (int)reader["BrandID"],
                    Course = (int)reader["Course"],
                    ID = (int)reader["ID"],
                    ModelID = (int?)reader["ModelID"],
                    RegNumber = (string)reader["RegNumber"],
                    VIN = (string)reader["VIN"]
                };
            }
        }
    }