我在使用代码优先的EF中看到了几个关于多对多关系的例子,但我遇到了一个我不确定如何解决的情况。
我试图模拟这种情况
实体是客户,访客,活动 1.)客户注册活动 2.)每个客户都有他可以带来的客人参加他注册的活动 (例如,如果他已登记参加活动1并且数量为3,则可以指定2位客人)
我尝试使用一个简单的场景,我做了很多关系的黑客和事件,它工作正常, 我可以使用events.guests导航属性
将访客添加到活动中但是我需要让它与客户合作,我很难绕过它,客户会在哪里适应这个模型?
public class Guest
{
public int GuestId { get; set; }
public string GuestName { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public virtual ICollection<Guest> Guests { get; set; }
}
这会生成一个映射表GuestEvent,它具有GuestId,EventId
据我所知,映射表应该与添加的客户实体一样 customerId,EventId,GuestId 但是我如何设置呢?
答案 0 :(得分:1)
CustomerEvent
类需要保留Guests
,因为客户需要链接到特定客户和特定事件。同一位客人可以参加不同的活动,或受到不同客户的邀请。
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public virtual ICollection<CustomerEvent> CustomerEvents { get; set; }
}
publix class CustomerEvent
{
public int CustomerEventId { get; set; }
public virtual int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
public virtual int EventId { get; set; }
public virtual Event Event { get; set; }
public virtual ICollection<Guest> Guests { get; set; }
}
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public virtual ICollection<CustomerEvent> CustomerEvents { get; set; }
}
public class Guest
{
public int GuestId { get; set; }
public string GuestName { get; set; }
public virtual ICollection<CustomerEvent> CustomerEvents { get; set; }
}
答案 1 :(得分:0)
这样的事情应该有效:这假设客户和事件之间的关系是1:1,所有名称信息都在Guest对象上......
public class Guest
{
public int GuestId { get; set; }
public string GuestName { get; set; }
public int CustomerId { get; set; }
public virtual Customer Patron { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public virtual ICollection<Guest> Guests { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public int EventId { get; set; }
public virtual ICollection<Guest> Guests { get; set; }
public virtual Event Event { get; set; }
}