如何为一对多关系设置中间 table?

How to have intermediate table for a 1 to many relationship?

我有一个模型class:

public class UserProfile
{
        public string UserID { get; set; }
        public string Name{ get; set; }
        public ICollection<AddressMaster> AddressMaster { get; set; }
}

上面的 class 与下面给出的 AddressMaster 模型 class 有一对多的关系:

public class AddressMaster
{
        public string AddrID{ get; set; }
        public string AddressLine1{ get; set; }
        public UserProfile UserProfile { get; set; }
        public TheatreLocation TheatreLocation { get; set; }
}

问题是,还有一个模型也与 addressmaster 具有一对多关系,即:

public class TheatreLocation
{
        public string LocationID { get; set; }
        public string Name{ get; set; }
        public ICollection<AddressMaster> AddressMaster { get; set; }
}

因此,我们如何才能在 addressmaster 和 userprofile 之间有一个中间 table 以及另一个这样的 table b/w addressmaster 和 theatre?

还是我把整个概念弄错了?

谢谢。

您的 table 定义可能会像这样结束:

UserProfile
    UserId PK

Theather
    TheatreId PK

Address
    AddrID PK
    AddressLine1 

UserAddress
    UserId PK & FK
    AddressId FK

TheatreAddress
    TheatreID PK & FK
    AddressId FK

这是很好的规范化 - 即您在数据库中有一个通用的 'address' table。多个实体可能有一个地址,并且与地址之间存在一对多或多对多的关系,但是一个特定的地址只需要记录一次。

中间的PK table 仅在UserId(例如)上确保这是一对多而不是多对多。

So instead of having foreign key at the addressmaster, how can we have a intermediate table between addressmaster and the userprofile & another such table b/w addressmaster and theatre?

如果您不想设置任何外键并添加一个中间值 table.Design,如下所示:

public class UserProfile
{
    [Key]
    public string UserID { get; set; }
    public string Name { get; set; }       
}
public class AddressMaster
{
    [Key]
    public string AddrID { get; set; }
    public string AddressLine1 { get; set; }
}
public class UserAddress
{       
    [Key]
    public string AddrID { get; set; }
    public string UserID { get; set; }
}

将主键添加到中间table UserAddressAddrId只能有一个值,但UserID可以有多个值,如one-to-many关系。

Or am i getting the whole concept wrong?

没什么wrong.Using 导航属性 像你做的也不错。