本文介绍了EF代码第一个相关实体上下文失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

邓肯如何正确地命名。我有两个实体在m:n关系:成员和角色。

  public class Role 
{
public int Id {get;组; }
public string标题{get;组; }

public ICollection< Member> MembersInRole {get;组;
}

public class Member
{
public int Id {get;组; }
public string Name {get;组; }
public string Password {get;组; }
public string Email {get;组; }

public ICollection< Role>角色{get;组; }
}

我已经制作了一些种子数据: br>



并写了测试:



问题是,我的会员实体没有角色分配,即使我在上下文中创建它们(如图所示)。我不知道怎么了数据库中的表似乎可以。我不确定上下文实例是否没有错误。但是应该是可以的,因为我一直在使用种子数据。

解决方案

尝试通过明确的方式加载角色:

 会员admin = db.Members.Include(Roles)。FirstOrDefault(m => m.Name ==Admin); 


Dunno how to name this properly. I have two entities in m:n relationship: Member and Role.

public class Role
{
    public int Id { get; set; }
    public string Title { get; set; }

    public ICollection<Member> MembersInRole { get; set; }
}

public class Member
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }

    public ICollection<Role> Roles { get; set; }
}

I have made some seed data:
http://i56.tinypic.com/2vjvj1w.png

And wrote test:
http://i54.tinypic.com/112916b.png

The problem is, that my Member entity has no roles assigned, even when I created them in context (as you can see at images). I don't know what's wrong. Tables in database seems to be ok. I am not sure if there isn't something wrong with context instances. But it should be ok, becuase I am working with seed data all the time.

解决方案

Try to eager-load the roles by including them explicitly:

Member admin = db.Members.Include("Roles").FirstOrDefault(m => m.Name == "Admin");

这篇关于EF代码第一个相关实体上下文失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:12