我想通過使用實體框架中的存儲過程的代碼首先創建刪除用戶。但是我對Entity Framework很陌生,所以我不知道如何做到這一點。任何人都可以讓我知道我該怎麼做?如何使用實體框架代碼優先調用存儲過程?
這是我到目前爲止的代碼:
存儲在SQL Server程序:
CREATE PROCEDURE [dbo].[DeleteUserById]
@UserId bigint
AS
BEGIN
DELETE FROM [dbo].[Users]
WHERE id = @UserId
END
現在現在可以此存儲過程可以在代碼中使用?我不知道任何人請告訴我。
這是我的類模型構造器:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection")
{
}
public virtual DbSet<UserInfo> UserInfo { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public virtual ObjectResult<List<Users>> GetUsers()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<List<UserInfo>>("GetUsers");
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Users>()
.MapToStoredProcedures(s => s.Delete(u => u.HasName("DeleteUserById", "dbo")
.Parameter(b => b.id, "userid"))
);
}
}
這是我在控制器刪除方法:
public string DeleteUsers(int id)
{
//here how can call this sp and delete this user
}
如果有人知道的話,請幫我完成這個任務。
[這個問題](http://stackoverflow.com/questions/643880/commandtype-text-vs-commandtype-存儲過程)描述了兩種可能的方式及其好處。 –
但在這段代碼中,我該如何寫這段代碼是正確還是錯誤? – coderwill
您可以使用實體框架linq命令刪除用戶。 [檢查此答案](http://stackoverflow.com/questions/31672899/how-do-i-delete-single-record-from-table-using-ef-6-1-1)。謝謝 –