【问题标题】:default constructor for POCO entity in EF6 Code first approachEF6 代码优先方法中 POCO 实体的默认构造函数
【发布时间】:2016-10-20 17:07:08
【问题描述】:

我是 EF 的新手。 我正在使用 EF6 Code First 方法制作应用程序,我已将所有 POCO 实体派生自定义 Id 的基类。 我不知道如何为处理多对多关系的实体声明构造函数。 例如:

我有这个实体:

 public partial class ArqAppRole
    {
        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ApplicationId { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int RoleId { get; set; }

        public DateTime SinceDate { get; set; }

        public DateTime? UntilDate { get; set; }

        public bool IsActive { get; set; }

        public virtual ArqApplication ArqApplication { get; set; }

        public virtual ArqRole ArqRole { get; set; }
    }

这是由 EF 自动生成的,我想要将它的超类设置为 BaseEntity 类,该类有一个默认构造函数,该构造函数设置它 Id,我不知道如何处理 ArqApplication 和 ArqRole 属性及其属性 ID

我的基类是:

public abstract class BaseEntity
    {
        private object _id;

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public object Id
        {
            get
            {
                return _id;
            }
            protected set
            {
                _id = value;
            }
        }

        protected BaseEntity() : this(null) { }

        protected BaseEntity(object id)
        {
            _id = id;
        }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc entity-framework ef-code-first


    【解决方案1】:

    您可以将 Id 保留在基类中,在此用例中,您必须使用 Fluent API 配置您的一对一关系。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      modelBuilder.Entity<ArqAppRole>()
                  .HasRequired(s => s.Application) 
                  .WithRequiredPrincipal(ad => ad.ArqAppRole); 
    } 
    

    Fluent API 将首先覆盖您的代码。但是将 Id 放在基类中是一种不好的做法,您必须到处寻找技巧。就用常规的方式,按应有的方式使用EF。

    更多信息:Code first self referencing foreign key (more than one)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多