我的POCO设置如下:
public class Notification : BaseClass
{
public User Receiver { get; set; }
[Required, Index]
public long ReceiverID { get; set; }
public virtual User ContextualUser { get; set; }
public long? ContextualUserID { get; set; }
public virtual User Actor { get; set; }
public long? ActorID { get; set; }
public string Content { get; set; }
public string Uri { get; set; }
[Required]
public string Type { get; set; }
}
我的基类只有 三个属性:ID
,CreateDate
和IsDeleted
,没有一个与User
类相关:
public abstract class BaseClass
{
[Key]
public long ID { get; set; }
[Required]
public DateTime CreateDate { get; set; }
public bool IsDeleted { get; set; }
public BaseClass()
{
CreateDate = DateTime.UtcNow;
}
}
但是,Entity Framework会创建一个额外的列User_ID
,始终为null ,如下所示:
它显然没有映射到任何东西。我的其他实体(无论是否来自相同的基类)都没有此幻像列。为什么要创建此列?我使用SQL Azure在EF 6.1.3代码优先。
更新:我还在PM控制台中运行了update-database
但没有任何改变,我仍然有这个专栏。
更新2:甚至在列上定义了索引和外键。我已经尝试删除它(它还不是一个实时应用程序)但它被索引引用:
alter table notifications drop column User_ID
Msg 5074, Level 16, State 1, Line 1
The index 'IX_User_ID' is dependent on column 'User_ID'.
Msg 5074, Level 16, State 1, Line 1
The object 'FK_dbo.Notifications_dbo.Users_User_ID' is dependent on column 'User_ID'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN User_ID failed because one or more objects access this column.
答案 0 :(得分:5)
我的User
类的导航属性配置不正确。由于Notification
类没有名为User
的属性,而是Receiver
,因为我忘了添加正确的名称(Receiver)作为反向属性我的User
类有一个Notifications
集合,这个额外字段用于将从{/ 1>} 导航到 User
秒。我已将注释Notification
添加到[InverseProperty("Receiver")]
类的我的集合中,现在它可以正常运行。
答案 1 :(得分:0)
您可以使用数据公式:
public abstract class BaseClass
{
[Key]
public long ID { get; set; }
[Required]
public DateTime CreateDate { get; set; }
public bool IsDeleted { get; set; }
public BaseClass()
{
CreateDate = DateTime.UtcNow;
}
}
public class Notification : BaseClass
{
[ForeignKey("ReceiverID")]
[InverseProperty("Receivers")]
public User Receiver { get; set; }
[Required, Index]
public long ReceiverID { get; set; }
[ForeignKey("ContextualUserID")]
[InverseProperty("ContextualUsers")]
public virtual User ContextualUser { get; set; }
public long? ContextualUserID { get; set; }
[ForeignKey("ActorID")]
[InverseProperty("Actors")]
public virtual User Actor { get; set; }
public long? ActorID { get; set; }
public string Content { get; set; }
public string Uri { get; set; }
[Required]
public string Type { get; set; }
}
public class User
{
[InverseProperty("Receiver")]
public ICollection<Notification> Receivers { get; set; }
[InverseProperty("ContextualUser")]
public ICollection<Notification> ContextualUsers { get; set; }
[InverseProperty("Actor")]
public ICollection<Notification> Actors { get; set; }
}
了解更多信息: