0

我在我的數據庫中有一個存儲過程(sp_create_user),它在我的Users表中創建一個用戶。這是我的存儲過程的定義:存儲過程的參數少於關聯對象

ALTER PROCEDURE sp_create_user 
    @Username nvarchar(50), 
    @Password nvarchar(50), 
AS 
BEGIN 
    -- SQL STATMENTS 
END 

User對象在C#中是這樣的:

public partial class User 
{ 
    public User() 
    { 
    } 

    public int UserId { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

這是我的EF用戶實體插入映射到存儲過程:

modelBuilder.Entity<User>().MapToStoredProcedures(
    s => 
     s.Insert(i => i.HasName("sp_create_user")) 
); 

當我嘗試執行新的用戶創建時,我得到一個例外,即發送到存儲過程的參數數量太大。跟蹤查詢後,我發現它向存儲過程發送User類所具有的所有字段。

如何告知EF只發送存儲過程的相關字段?

+1

附註如果這是**的SQL Server **:你應該** **不爲存儲過程使用'sp_'前綴。微軟[留作自己使用前綴(見*命名存儲過程*)(http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),和你將來有可能冒着名字衝突的風險。 [這對你的存儲過程性能也是不利的](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix)。最好只是簡單地避免使用'sp_'並將其他內容用作前綴 - 或者根本沒有前綴! – 2014-11-20 20:49:30

+1

你不能只是將參數添加到SP? :) – 2014-11-20 21:24:22

+0

這就是我最終做的:( – developer82 2014-11-20 22:14:23

回答

1
... 
[System.ComponentModel.DataAnnotations.Schema.NotMapped] 
public int UserId { get; set; } 

public string Username { get; set; } 
public string Password { get; set; } 

[System.ComponentModel.DataAnnotations.Schema.NotMapped] 
public string FirstName { get; set; } 

[System.ComponentModel.DataAnnotations.Schema.NotMapped] 
public string LastName { get; set; } 
... 

您也可以嘗試以下方法,如果你不想修改類:

modelBuilder.Entity<User>().Ignore(u => u.UserId); 
+0

是否有一種方法可以在映射中定義它而不會干擾實體類? – developer82 2014-11-20 20:37:37

+0

什麼是「忽略」?它會對常規EF更新產生影響嗎?因爲更新我想發送一些我不發送SP插入的字段 – developer82 2014-11-20 21:10:04