Juanma
Juanma

Reputation: 925

default constructor for POCO entity in EF6 Code first approach

I'm new in EF. I'm making an app with EF6 Code First approach, I've made all my POCO entities to derive from a base class which define an Id. What I don't know is how to declare the constructor for an entity that handles many to many relatioship. For example:

I've got this entity:

 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; }
    }

this was auto-generated by EF, what I want is to set it superclass to BaseEntity class that has a default constructor which sets it Id and I don't know how to handle ArqApplication and ArqRole properties and their propper Ids

My base class is:

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;
        }
}

Upvotes: 2

Views: 769

Answers (1)

Bassam Alugili
Bassam Alugili

Reputation: 17003

You can leave the Id on the base class and in this use case you have to configure your one-to-one releshinship with Fluent API.

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

Fluent API will override your code first. But putting the Id in the base class is a bad practice and you have to find tricks everywhere. Just use the conventional way and use the EF as should be used.

More info: Code first self referencing foreign key (more than one)

Upvotes: 1

Related Questions