这是实现参与集合和EF代码首先多对多关系的方式吗?

时间:2014-03-21 18:40:45

标签: c# entity-framework

我遇到的情况是我到达的代码与我找到的任何示例都不匹配,所以我想知道我是否遗漏了一些东西。

基本上,我想要一个EF代码优先实体,其中包含参与多对多关系的实体集合。

然后,我希望能够:

  • 在创建实体的同时添加到集合
  • 未收到有关从构造函数
  • 访问虚拟成员的警告

这就是我所拥有的:

public class NotificationUser
{
    private ICollection<NotificationUserGroup> _userGroups = new HashSet<NotificationUserGroup>();

    public int UserId { get; set; }

    public string UserName { get; set; }

    public bool IsActive { get; set; }

    public virtual ICollection<NotificationUserGroup> UserGroups
    {
        get { return _userGroups; }
        set { _userGroups = value; }
    }
}

是否有更好/不同的方式来实现我的目标?

1 个答案:

答案 0 :(得分:0)

此示例可能会有所帮助

public class NotificationUser
{
    public NotificationUser()
    {
        UserGroups = new HashSet<NotificationUserGroup>();
    }

    public int NotificationUserId { get; set; }
    public string UserName { get; set; }
    public bool IsActive { get; set; }
    public virtual ICollection<NotificationUserGroup> UserGroups { get; set; }
}

public class NotificationUserGroup
{
    public int NotificationUserGroupId { get; set; }
    public string GroupName { get; set; }
}

public class Context : DbContext
{
    public Context()
        : base()
    {

    }
    public DbSet<NotificationUser> NotificationUsers { get; set; }
    public DbSet<NotificationUserGroup> NotificationUserGroup { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<Context>());

        using (var ctx = new Context())
        {
            var user = new NotificationUser() { UserName = "Name1" };
            user.UserGroups.Add(new NotificationUserGroup() { GroupName = "Group1" });
            user.UserGroups.Add(new NotificationUserGroup() { GroupName = "Group2" });
            ctx.NotificationUsers.Add(user);

            ctx.SaveChanges();
        }

        using (var ctx = new Context())
        {
            foreach (var user in ctx.NotificationUsers)
            {
                foreach (var group in user.UserGroups)
                    Console.WriteLine("Group Id: {0}, Group Name: {1}, UserName: {2}", group.NotificationUserGroupId, group.GroupName,user.UserName);
            }

            foreach (var group in ctx.NotificationUserGroup)
            {
                Console.WriteLine("Group Id: {0}, Group Name: {1}", group.NotificationUserGroupId, group.GroupName);
            }
        }

        Console.ReadKey();
    }
}