首页 > 代码库 > Entity Framework Code First执行SQL语句、视图及存储过程

Entity Framework Code First执行SQL语句、视图及存储过程

1、Entity Framework Code First查询表或视图

var provincelist = ctx.Provinces.SqlQuery("SELECT TOP 10 * FROM Province");
    foreach (var province in provincelist)
    {
        Console.WriteLine("{0}-{1}-{2}", province.ProvinceID, province.ProvinceNo, province.ProvinceName);
    }
    var provincelist = ctx.Database.SqlQuery<TempProvince>("SELECT TOP 10 ProvinceNo,ProvinceName FROM Province");
    foreach (var province in provincelist)
    {
        Console.WriteLine("{0}-{1}", province.ProvinceNo, province.ProvinceName);
    }

3、Entity Framework Code First执行存储过程

CREATE PROCEDURE GetCityByProvinceID
(
    @ProvinceID INT
)
AS
    SELECT * FROM City
    WHERE ProvinceID = @ProvinceID
using (var ctx = new PortalContext())
{
    var cityList = ctx.Cities.SqlQuery("dbo.GetCityByProvinceID @p0", 3);
    foreach (var city in cityList)
    {
        Console.WriteLine("{0}-{1}-{2}-{3}", city.CityID, city.ProvinceID, city.CityNo, city.CityName);
    }
}

存储过程多个输入参数:

var country = "Australia";
var keyWords = "Beach, Sun";
var destinations = context.Database.SqlQuery<DestinationSummary>("dbo.GetDestinationSummary @p0, @p1", country, keyWords);

 

Entity Framework Code First执行SQL语句、视图及存储过程