从EF 6.0 Code First调用存储过程不会插入记录

时间:2014-02-27 00:20:17

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

我是EF的新手,我正在玩这个。当我尝试从存储库调用我在数据库中创建的存储过程时,我遇到了困难。我运行SQL Server Profiler并且没有执行存储过程。任何人都可以指出我正确的方向吗?

我使用的是VS 2012和SQL Server 2008 R2。我将存储库模式与工作单元一起使用,并在服务层的Commit上调用Uow(如果我遵循这种方法,不确定是否必须调用commit,因为文档说明了结果数据库上下文从不跟踪此查询)。

任何帮助都会非常感激

到目前为止我做过的事情 1.在存储的proc名称前面加上和不加Exec关键字

我的存储库代码:

public class CarRentalUserRepository :  RepositoryBase<CarRentalUser>
{
    public override void Add(CarRentalUser user)
    {
       using (var cxt = this.DataContext)
       {
           var userId = new SqlParameter { ParameterName = "@UserId", Value = 0, Direction = System.Data.ParameterDirection.Output };
           var roleId = new SqlParameter("@RoleId", user.RoleId);
           var firstName = new SqlParameter("@FirstName", user.FirstName);
           var lastName = new SqlParameter("@LastName", user.LastName);
           var email = new SqlParameter("@EmailAddress", user.EmailAddress);
           var passsword = new SqlParameter("@Password", user.Password);
           var active = new SqlParameter("@IsActive", user.IsActive);

           //I see for some reason,the connection state is closed.So am opening that connection here(Don't know why)
           if (cxt.Database.Connection.State == System.Data.ConnectionState.Closed)
           {
              cxt.Database.Connection.Open();
           }

           var result =  cxt.Database.SqlQuery<CarRentalUser>(" exec CarRental_InsertUser @UserId, @RoleId, @FirstName, @LastName, @EmailAddress, @Password, @IsActive", userId, roleId, firstName, lastName, email, passsword, active);

           if (result != null)
           { 
           }
        }
    }

public class RepositoryBase<T> where T : class
{
    private CarRentalDbContext _dbcontext = null;
    private readonly IDbSet<T> dbset;

    public RepositoryBase(IDatabaseFactory databseFactory)
    {
       //DatabaseFactory = databseFactory;
       this.DataContext = databseFactory.DbContext;
       dbset = DataContext.Set<T>();
    }

    //protected IDatabaseFactory DatabaseFactory { get;private set; }
    protected CarRentalDbContext DataContext
    {
       get { return _dbcontext; }
       set { _dbcontext = value; }
    }

    public virtual void Add(T entity)
    {
       dbset.Add(entity);
    }

    public virtual void Update(T entity)
    {
       dbset.Attach(entity);
       DataContext.Entry(entity).State = EntityState.Modified;
    }

    public virtual void Delete(T entity)
    {
       dbset.Remove(entity);
    }

    public virtual void Delete(Expression<Func<T, bool>> predicate)
    {
       IEnumerable<T> objects = dbset.Where<T>(predicate).AsEnumerable();
       if (objects != null && objects.Any())
       {
           foreach (T obj in objects)
           {
               dbset.Remove(obj);
           }
       }
    }

    public virtual T GetById(long Id)
    {
       return dbset.Find(Id);
    }

    public virtual T GetById(string Id)
    {
       return dbset.Find(Id);
    }

    public virtual T Get(Expression<Func<T,bool>> predicate)
    {
       return dbset.Where(predicate).FirstOrDefault<T>();
    }

    public virtual IEnumerable<T> GetAll()
    {
       return dbset.ToList();
    }

    public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> predicate)
    {
       return dbset.Where(predicate).AsEnumerable<T>();
    }
}

public class UnitOfWork : IUnitOfWork
{
    //private readonly IDatabaseFactory databaseFactory;
    private CarRentalDbContext _dbContext;

    public UnitOfWork(IDatabaseFactory databaseFactory)
    {
        this.DataContext = databaseFactory.DbContext;
    }

    public void Commit()
    {
        if (DataContext != null)
        {
            DataContext.Commit();
        }
    }

    public CarRentalDbContext DataContext
    {
        get { return _dbContext; }
        set { _dbContext = value; }
    }
}

public interface IUnitOfWork
{
   void Commit();
}

public class CarRentalDbContext : DbContext
{
    public CarRentalDbContext()
        : base("CarRental_Connection_String")
    {
        var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
        Database.SetInitializer<CarRentalDbContext>(null);
    }        

    public DbSet<CarRentalUser> Users { get; set; }

    public virtual void Commit()
    {
        base.SaveChanges();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Configurations.Add(new CarRentalUserMap());
        modelBuilder.Configurations.Add(new CarRentalRoleMap());
    }
}

我的存储过程

Create PROCEDURE dbo.CarRental_InsertUser (
    @UserId INT OUTPUT
    ,@RoleId INT
    ,@FirstName VARCHAR(50)
    ,@LastName VARCHAR(50)
    ,@EmailAddress VARCHAR(25)
    ,@Password VARBINARY(500)
    ,@IsActive BIT
    )
AS
BEGIN
    INSERT INTO [CarRental].[dbo].[CarRentalUser]
           ([RoleId]
           ,[EmailAddress]
           ,[FirstName]
           ,[LastName]
           ,[Password]
           ,[CreatedDtm]
           ,[UpdateDtm]
           ,[IsActive])
     VALUES
           (
               @RoleId,
               @EmailAddress,
               @FirstName,
               @LastName,
               @Password,
               GETDATE(),
               null,
               1           
           )

    set @UserId = SCOPE_IDENTITY();
END

1 个答案:

答案 0 :(得分:0)

我想我发现了这个问题。我对进行数据库调用的部分进行了以下更改

var result =  cxt.Database.SqlQuery<int>("CarRental_InsertUser @UserId,@RoleId,@FirstName,@LastName,@EmailAddress,@Password,@IsActive",
                                                                         userId,roleId,firstName,lastName,email,passsword,active);

                   if (result != null)
                   {
                       retVal = result.Single();
                   }

因为我的存储过程返回一个int输出参数。我注意到的一件事是,程序只在我调用result.Single()

后执行。