【问题标题】:How can I get data from another entity using class in between in Entity Framework如何使用实体框架中的类从另一个实体获取数据
【发布时间】:2016-03-12 00:44:36
【问题描述】:

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

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 还是多个?
  • 我使用了从 DbContext @ErikPhilips 继承的上下文
  • 评论没有回答问题。

标签: c# asp.net-mvc asp.net-mvc-4 entity-framework-6


【解决方案1】:

这是我的 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());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2013-11-16
    相关资源
    最近更新 更多