开发者

EF Code First Many to many relation store additional data in link table

How do I store additional fields in the "link table" that is automagically created for me if I have two entities associated as having a many to m开发者_StackOverflowany relationship?

I have tried going the "two 1 to many associations"-route, but I'm having a hard time with correctly configuring the cascading deletion.


Unless those extra columns are used by some functions or procedures at the database level, the extra columns in the link table will be useless since they are completely invisible at the Entity Framework level.

It sounds like you need to re-think your object model. If you absolutely need those columns, you can always add them later manually.


You will most likely need to expose the association in your domain model.

As an example, I needed to store an index (display order) against items in an many-to-many relationship (Project <> Images).

Here's the association class:

public class ProjectImage : Entity
{
    public Guid ProjectId { get; set; }
    public Guid ImageId { get; set; }
    public virtual int DisplayIndex { get; set; }       
    public virtual Project Project { get; set; }
    public virtual Image Image { get; set; }
}

Here's the mapping:

public class ProjectImageMap : EntityTypeConfiguration<ProjectImage>
{
    public ProjectImageMap()
    {
        ToTable("ProjectImages");
        HasKey(pi => pi.Id);
        HasRequired(pi => pi.Project);
        HasRequired(pi => pi.Image);
    }
}

From Project Map:

HasMany(p => p.ProjectImages).WithRequired(pi => pi.Project);

Maps to the following property on project:

public virtual IList<ProjectImage> ProjectImages { get; set; }

Hope that helps

Ben


Suppose there is a many-to-many association between two types: User and Message, and the association class is defined as UserMessageLink with additional properties.

public class User {
    public int Id {get;set;}
}

public class Message {
    public int Id {get;set;}
}

//The many-to-many association class with additional properties
public class UserMessageLink {
    [Key]
    [Column("RecieverId", Order = 0)]
    [ForeignKey("Reciever")]
    public virtual int RecieverId { get; set; }

    [Key]
    [Column("MessageId", Order = 1)]
    [ForeignKey("Message")]
    public virtual int MessageId { get; set; }

    public virtual User Reciever { get; set; }
    public virtual Message Message { get; set; }

    //This is an additional property
    public bool IsRead { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜