使用存储过程实体框架从表中获取列表

时间:2014-04-02 08:31:59

标签: c# sql sql-server entity-framework stored-procedures

我使用相同的存储过程在条件库上插入和获取数据。

存储过程 -

   ALTER PROCEDURE dbo.sp_SaveUserRole
    @company_name nvarchar(50)=null,
    @address nvarchar(250)=null,
    @mobileno int =0,
    @phoneno int=0,
    @faxno int=0,
    @email nvarchar(250)=null,
    @regno int=0,
    @establish_date datetime=null,
    @cond int=0

    AS
    if(@cond=1)
    begin
    insert into Company (company_name,address,mobileno,phoneno,faxno,regno,email,establish_date) values (@company_name,@address,@mobileno,@phoneno,@faxno,@regno,@email,@establish_date)
    end
    else if(@cond=2)
    begin
    select * from company where isactive = 'True';
    end

        RETURN

在使用实体框架插入数据时,我正在这样做 -

public ActionResult SaveRole(CompanyModel cmp)
    {
        var company_name = cmp.Company_Name;
        var regno = cmp.regNo;
        var mobileno = cmp.mobileNo;
        var phoneno = cmp.phoneNo;
        var establish_date = cmp.establish_Date;
        var email = cmp.emaiL;
        var address = cmp.Address;
        var faxno = cmp.faxNo;
        db.sp_SaveUserRole(company_name, address, mobileno, phoneno, faxno, email, regno, establish_date,1);
        return Json(new { success = true });

注意 - 这里条件是1所以它插入数据过程。

尝试获取列表

 var list = db.sp_SaveUserRole("", "", 0, 0, 0, "", 0, null, 2).ToList();

我尝试了这种从表中获取数据的方法,我必须将必要的参数传递给此过程调用。虽然我想把这个程序仅用于我在那里提到的第二个条件。

仅适用于第二个条件如何在不传递参数的情况下修改此过程?

1 个答案:

答案 0 :(得分:1)

我不会使用存储过程,而是将公司表作为实体添加到edmx中,并通过代码访问它。

这样,您可以使用LINQ来访问所需的数据,而不是将@ Cont = 2传递给存储过程,因为SQL看起来非常基本。

然后,您可以从存储过程中删除那条SQL,因为混合插入选项并不合适。

e.g。

// For insert
if (cont == 1)
{
   // Call your stored proc here

   // or if you add the company table to EF you can use the Insert use the Add 
   // e.g. Rough Example
   _yourEntities.Companies.Add(cmp);

   // Update the DB
   _yourEntities.SaveChanges();
}
else
{
   var companies = _yourEntities.Companies.Where(c => c.isactive == 'True');
}

如果这个解决方案不是一个选项,我仍然希望将存储过程分成两部分,以便轻松生活。

理想情况下,当您使用Entity Framework并希望从单个表中插入和选择时,如果将公司表作为实体添加到EF中,则可以免费获得此功能。

相关问题