【问题标题】:How to return data that has a many to many relationship如何返回具有多对多关系的数据
【发布时间】:2015-02-13 19:57:35
【问题描述】:

我不得不将一对多的关系改为多对多的关系。前一个用户在注册时被分配了一个 companyId。他们可以从数据库返回的唯一文档是由我的 Web Api 中的 where 语句控制的。现在可以为用户分配许多公司,我需要更改 where 语句来做同样的事情。

错误

Error   1   Operator '==' cannot be applied to operands of type 'int' and 'System.Collections.Generic.ICollection<TransparentEnergy.Models.Company>'    C:\Development\TransparentEnergy\TransparentEnergy\ControllersAPI\apiDocumentUserController.cs  31  33  TransparentEnergy

ApiController

   public IEnumerable<DocumentResult> Get()
    {
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var user = manager.FindById(User.Identity.GetUserId());

        using (var context = new ApplicationDbContext())
        {
            return context.Documents
                .Where(j => j.CompanyId == user.Companies)
          .ToResults();
        }

    }

 public class Company
{
    public int CompanyId { get; set; }
    public string CompanyName { get; set; }

    public List<Document> Documents { get; set; }
    public ICollection<ApplicationUser> Users { get; set; } 
}

 public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity>
        GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager
            .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
    public string Name { get; set; }
    public ICollection<Company> Companies { get; set; }
}

更新 连接表

 public class UserCompany
{
    [Key]
    public int UCompanyId { get; set; }

    public string Id { get; set; }
    public int CompanyId { get; set; }
 }

 public class Company
  {
    public int CompanyId { get; set; }
    public string CompanyName { get; set; }

    public int UserCompanyId { get; set; }
    public virtual UserCompany UserCompany { get; set; }

   }

 public class ApplicationUser : IdentityUser
   {
     public async Task<ClaimsIdentity>
        GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
     {
        var userIdentity = await manager
            .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
     }
     public int UserCompanyId { get; set; }
    public virtual UserCompany UserCompany { get; set; }
   }

控制器

  public List<Document> GetDocuments()
    {
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var user = manager.FindById(User.Identity.GetUserId());
        using (var context = new ApplicationDbContext())
        {
            return context.Documents
                .Where(j => j.CompanyId == user.UserCompany.UCompanyId)
                .ToList();
        }
    }

错误

非静态方法需要一个目标。

堆栈跟踪

在 System.Reflection.RuntimeMethodInfo.CheckConsistency(对象目标) 在 System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj,BindingFlags invokeAttr,Binder binder,Object[] 参数,CultureInfo 文化) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object[] 参数,CultureInfo 文化) 在 System.Reflection.RuntimePropertyInfo.GetValue(Object obj,BindingFlags invokeAttr,Binder binder,Object[] index,CultureInfo 文化) 在 System.Reflection.RuntimePropertyInfo.GetValue(对象 obj,对象 [] 索引) 在 System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me, Object instance, Object& memberValue) 在 System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.TryEvaluatePath(表达式表达式,ConstantExpression& constantExpression) 在 System.Data.Entity.Core.Objects.ELinq.QueryParameterExpression.EvaluateParameter(对象 [] 参数) 在 System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery1.c__DisplayClass7.b__6() 在 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery1.c__DisplayClass7.b__5() 在 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery1..GetEnumerator>b__0() 在 System.Data.Entity.Internal.LazyEnumerator1.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 源) 在 c:\Development\TransparentEnergy\TransparentEnergy\ControllersAPI\apiDocumentUserController.cs:line 29 中的 TransparentEnergy.ControllersAPI.apiDocumentUserController.GetDocuments() 在 lambda_method(闭包,对象,对象 []) 在 System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.c__DisplayClass10.b__9(对象实例,对象 [] 方法参数) 在 System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(对象实例,对象 [] 参数) 在 System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext 控制器上下文,IDictionary`2 参数,CancellationToken 取消令牌)

【问题讨论】:

    标签: entity-framework-6 asp.net-web-api2


    【解决方案1】:

    我不知道实体框架语法的细节,但如果您在用户和公司之间有多对多关系,您需要创建一个名为“UserCompany”之类的关联表。该表将保存 User 和 Company 的主键作为外键,然后您可以拉出 UserCompany 主键以查看哪些用户与哪些公司相关。

    【讨论】:

    • 它创建了一个,UserCompanies。它有 ApplicationUser_Id 和 Company_CompanyId。表没有主键列
    • 我会进入实体框架为 UserCompanies 创建的模型对象的实际代码并手动添加主键。只需在模型中为该对象添加主键整数属性应该不会有太多工作。
    • 在创建密钥方面找到了一些帮助。谢谢你的帮助
    猜你喜欢
    • 2017-07-11
    • 2012-09-29
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多