繁体   English   中英

如何在Entity Framework中使用介于两者之间的类从另一个实体获取数据

[英]How can I get data from another entity using class in between in Entity Framework

我有一个使用ASP.NET MVC和Entity Framework的项目。 这是我的实体:

public class Event
{
    public Event()
    {
        UserEvent = new HashSet<UserEvent>();
    }

    public int EventId { get; set; }
    public string EventName { get; set; }
    public string Description { get; set; }
    [DataType(DataType.Date)]
    public DateTime StartDate { get; set; }
    [DataType(DataType.Date)]
    public DateTime EndDate { get; set; }
    public string Time { get; set; }
    public int NumberOfVolunteer { get; set; }
    public virtual ICollection<UserEvent> UserEvent { get; private set; }
}

这是我在两个实体中间的桌子

public class UserEvent
{
    public int UserId { get; set; }
    public int EventId { get; set; }
    public string Type { get; set; }
    public virtual Event Event { get; set; }
    public virtual User User { get; set; }
}

这是我的用户表。

public class User
{
    public User()
    {
        this.UserEvent = new HashSet<UserEvent>();
    }

    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public Gender? GenderType { get; set; }
    public virtual ICollection<UserEvent> UserEvent { get; private set; }
}

这是我控制器中的方法。

public ViewResult Index(string searchString = null, int userId = 0, string ingredients = null)
{
        var myEvents = _eventService.GetAllEnum();

        if (!String.IsNullOrEmpty(searchString))
        {
            myEvents = myEvents.Where(r => r.EventName.ToUpper().Contains(searchString.ToUpper()));
        }

        if (userId > 0)
        {
            myEvents = myEvents.Where(r => r.userId == userId).ToList();
        }
    }
}

我的问题是如何使用扩展方法或连接从事件类获取userId? 我是该领域的新手,我不知道要获取它,因为我想根据用户过滤Event

我添加中间表的想法是为了防止多对多关系,并且我还创建了自定义映射

注意:我已经创建了一个通用存储库

这是我的DbContext

public class MyFinalOneTwoHandsContext :DbContext
{
    public MyFinalOneTwoHandsContext()
        :base("Name=MyFinalOneTwoHandsContext")
    {
    }
    public DbSet<User> Users { get; set; }
    public DbSet<Event> Events { get; set; }
    public DbSet<UserEvent> UserEvents { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UserMap());
        modelBuilder.Configurations.Add(new EventMap());
        modelBuilder.Configurations.Add(new UserEventMap());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM