如何在Entity Framework中为第三个表添加额外的列? [英] How can i add extra column to third table in Entity Framework?
问题描述
用户
和通知
: public class User
{
[Key]
public int UserId {get;组; }
//其他公共属性
//导航属性
public virtual ICollection< Notification>通知{get;组;
}
public class Notification
{
[Key]
public int NotificationId {get ;组; }
//其他公共属性
//导航属性
public virtual ICollection< User>用户{get;组; }
}
我只是添加多对多
关系如下:
modelBuilder.Entity< User>()
.HasMany(u => u.Notifications)
.WithMany(t => t.Users)
.Map(m =>
{
m。 ToTable(UserNotifications);
m.MapLeftKey(UserId);
m.MapRightKey(NotificationId);
});
但是,如果我要为此表添加额外的列,那么该名称为'状态'?我以为我可以使用 AddColumn
,但是我如何访问这个列并获得它的价值?我该如何做到这一点?我想检查用户是否阅读通知。任何建议都会很好,谢谢。
你不能在关系中添加额外的字段,如状态。你需要有一个虚拟表格。
我认为你的问题与以下答案相同
在Fluent API中与多个字段进行多对多映射
可能这将有所帮助。
用户
通知_
您将状态字段字段的UserNotification(虚拟表) p>
Assume i have two entities, User
and Notification
:
public class User
{
[Key]
public int UserId { get; set; }
// other public properties
// Navigation Properties
public virtual ICollection<Notification> Notifications { get; set; }
}
public class Notification
{
[Key]
public int NotificationId { get; set; }
// other public properties
// Navigation Properties
public virtual ICollection<User> Users { get; set; }
}
I'm simply adding many-to-many
Relationship like this:
modelBuilder.Entity<User>()
.HasMany(u => u.Notifications)
.WithMany(t => t.Users)
.Map(m =>
{
m.ToTable("UserNotifications");
m.MapLeftKey("UserId");
m.MapRightKey("NotificationId");
});
But what happens if i want to add extra column to this table which name is 'Status' ? I thought i can use AddColumn
but then how can i access this column and get it's value ? How can i accomplish this? I want to check whether the user read notification or not. Any suggestions would be great,thanks.
You can't add extra field like "Status" in the relationship. You need to have a dummy table for that.
And i think your question is same as the following answer
Many to Many mapping with extra fields in Fluent API
May be this would help.
User
Notification
UserNotification (dummy table) where you put your Status field
这篇关于如何在Entity Framework中为第三个表添加额外的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!