2017-02-16 53 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