我有一个使用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
。
我添加中间表的想法是为了防止多对多关系,也是我创建自定义映射
注意:我创建了一个通用存储库
答案 0 :(得分:0)
这是我的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());
}
}