2017-02-16 21 views
0

我需要與身份表和自定義表 許多到很多關係,我已經在這answer 使用相同的邏輯,但問題我不能給新增加的許多許多表什麼如何更新多表到Asp.Net MVC 5與身份表和自定義表

這裏是我自己的代碼

ApplicationUser

public class ApplicationUser : IdentityUser 
{ 
    public ApplicationUser() 
    { 
     subjects = new HashSet<subject>(); 
    } 

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 
     return userIdentity; 
    } 
    public virtual ICollection<subject> subjects { get; set; } 
} 

主題

public class subject 
    {   
     public int subjectId { get; set; } 
     public string subjectCode { get; set; } 
     public virtual ICollection<ApplicationUser> buyers { get; set; } 
    } 

功能我很勞累與 想採取的用戶和subjectCode電子郵件與用戶和對象在表

public ActionResult addBuyer(FormCollection fc) 
{ 
    ApplicationUser tst = _context.Users.FirstOrDefault(b => b.Email.Equals(fc["Email"].ToString())); 
    var temp = _context.subjects.Include("buyers").Where(c => c.subjectCode.Equals(fc["SubCode"].ToString())); 
    temp.First().buyers.Add(tst); 
    return RedirectToAction("Index"); 
} 

鏈接在一起添加實體並且這是錯誤

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code 

Additional information: LINQ to Entities does not recognize the method 'System.String get_Item(System.String)' method, and this method cannot be translated into a store expression. 

回答

0

由於fc["Email"]fc["SubCode"]集合索引可能沒有SQL語法等同於LINQ到實體,而是試圖分配/從索引中提取純值轉換成字符串變量,並將它們傳遞到查詢:

public ActionResult addBuyer(FormCollection fc) 
{ 
    // assign ToString() methods into string variables 
    String email = fc["Email"].ToString(); 
    String subCode = fc["SubCode"].ToString(); 

    // pass only plain values into the query 
    ApplicationUser tst = _context.Users.FirstOrDefault(b => b.Email.Equals(email)); 
    var temp = _context.subjects.Include("buyers").Where(c => c.subjectCode.Equals(subCode)); 
    temp.First().buyers.Add(tst); 
    return RedirectToAction("Index"); 
} 

注意:您應該避免ToString()方法在this post中提到的LINQ查詢內部調用,使用SqlFunctions.StringConvert或其他一些聚合方法作爲替代方法。

相關的問題:

LINQ to Entities does not recognize the method 'System.String get_Item (System.String)',

LINQ to Entities does not recognize the method 'System.String get_Item(System.String)' method, and this method cannot be translated into a store expression