LINQ ASP .NET MVC动作结果创建

时间:2019-04-03 10:13:27

标签: sql-server asp.net-mvc

这是我的ActionResult Create方法的代码:

public ActionResult Create([Bind(Include = "FileStatusID, Name, MinValue, MaxValue")] fileStatusModel FILeStatusModel, TBL_FileStatus tBL_FileStatus) //include tem os valores que vamos inserir na view
{
    var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
    using (var query = new Core_DBEntities)
    {
        var query1 = ??????????????
    }
    if (ModelState.IsValid)
    {
        TBL_FileStatus item = new TBL_FileStatus()
        {
            Name = FILeStatusModel.Name,
            MinValue = FILeStatusModel.MinValue,
            MaxValue = FILeStatusModel.MaxValue,
            Ative = true,
            CreateDate = DateTime.Now,
            CreateBy = userID
        };

        db.TBL_FileStatus.Add(item);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View();
}

这是我的SQL查询:

DECLARE @p_valuemin INT
DECLARE @p_valuemax INT

SET @p_valuemin = 9   
SET @p_valuemax = 183

IF @p_valuemin >= @p_valuemax
    RAISERROR('@p_valuemin deve ser menor que o @p_valuemax', 16, 1)

SELECT *
FROM [TBL_FileStatus]
WHERE Ative = 1 AND ((@p_valuemin BETWEEN MinValue AND MaxValue) AND MaxValue <> @p_valuemin)
OR ((@p_valuemax BETWEEN MinValue AND MaxValue) AND MinValue <> @p_valuemax)
UNION
SELECT *
FROM [TBL_FileStatus]
WHERE Ative = 1 AND ((MinValue BETWEEN @p_valuemin AND @p_valuemax) AND MinValue <> @p_valuemax)
OR ((MaxValue BETWEEN @p_valuemin AND @p_valuemax) AND MaxValue <> @p_valuemin)

those 2 values will represent the textbox of create
SET @p_valuemin = 9   
SET @p_valuemax = 183

我的问题是:

我想将此SQL查询与ActionResult Create结合起来,以在单击创建按钮之前创建条件。

我该如何实现?

1 个答案:

答案 0 :(得分:1)

如果您需要调用存储过程,则Entity Framework具有SqlQuery()方法。

您可以像这样调用存储过程:

var p_valuemin = new SqlParameter
                     {
                         ParameterName = "p_valuemin",
                         Value = 9
                     };
var p_valuemax = new SqlParameter
                     {
                         ParameterName = "p_valuemax",
                         Value = 183
                     };

var query = "GetFileStatus @p_valuemin, @p_valuemax";

var result = db.Database.SqlQuery<GetFileStatus>(query, p_valuemin, p_valuemax).ToList();

这里p_valueminp_valuemax是您的SQL Server存储过程参数,如查询GetFileStatus中所述是您的存储过程名称,而GetFileStatus是您的结果模型,例如从存储过程中查询返回的结果实体

db.Database.SqlQuery<GetFileStatus>(query,p_valuemin, p_valuemax).ToList(); 

用于调用存储过程。

您的结果GetFileStatus模型看起来像

public class GetFileStatus
{
    public int FileStatusID { get; set; }
    public string Name { get; set; }
    public int MinValue { get; set; }
    public int MaxValue { get; set; }
    public bool Active { get; set; }
}

希望它能对您有所帮助,并让我知道是否需要更多信息。