none
Issues with Entity Framework 7 RRS feed

  • Question

  • HI,

    I have been using the User.cs and Person.cs entities and database context(DatabaseContext.cs) in entity framework 7. These 3 classes I have pasted in the end of this question. When I use the below code with those entities I am getting different errors as described below

     var userAccounts = from u in _userRepo.Get()
                                       join p in _perosnRepo.Get() on u.PersonID equals p.PersonID

                                       select new UserAccount { UserId = u.UserID, Username = p.Email, AccessDenied = u.AccountLocked.GetValueOrDefault(), OrganisationId = u.OrgID.GetValueOrDefault(), PersonId = u.PersonID.GetValueOrDefault() };

                    accounts = userAccounts != null ? userAccounts.Where(u => u.Username == Name) : null;

                    if (!accounts.IsNullOrEmpty())
                        user = accounts.FirstOrDefault()

    1. This is giving the error 

    "An item with the same key has already been added."

    2. If I remove the below lines from person.cs

     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<User> Users { get; set; } 

    And remove the below line from User.cs Class

    public virtual Person Person { get; set; }

    getting the below error

    "The instance of entity type 'Person' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values."

    Please provide the help on these errors.

    User.cs

    namespace Core.Data
    {
       
       
        using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
    
    
           [Table("User")]
        public partial class User
        {
            public int UserID { get; set; }
    
            public int? OrgID { get; set; }
    
            public int? OrgRoleID { get; set; }
    
            public int? PersonID { get; set; }
    
            [MaxLength(50)]
            public byte[] PasswordHash { get; set; }
    
            public bool? AccountLocked { get; set; }
    
            public DateTime? LastSignIn { get; set; }
    
            public virtual Person Person { get; set; }
        }
    }
    
    
    

    Person.cs

    namespace Core.Data
    {
       
        using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
       
    
        [Table("Person")]
        public partial class Person
        {
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
            public Person()
            {
                Users = new HashSet<User>();
            }
    
            public int PersonID { get; set; }
    
            [StringLength(50)]
            public string Salutation { get; set; }
    
            [StringLength(50)]
            public string FullName { get; set; }
    
            [StringLength(120)]
            public string Address { get; set; }
    
            [StringLength(50)]
            public string PostCode { get; set; }
    
            [StringLength(2)]
            public string CountryCode { get; set; }
    
            [StringLength(50)]
            public string Email { get; set; }
    
            [StringLength(50)]
            public string Phone { get; set; }
    
            public int? JobRoleID { get; set; }
    
            [StringLength(50)]
            public string JobTitle { get; set; }
    
            public int? PersonStatusID { get; set; }
    
            [StringLength(5)]
            public string TimeZoneCode { get; set; }
    
            [StringLength(2)]
            public string LanguageCode { get; set; }
    
            public int? ManagerID { get; set; }
    
            public DateTime? LastChanged { get; set; }
    
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<User> Users { get; set; }
        }
    }
    

    DatabaseContext.cs

    using Microsoft.Data.Entity;
    using System;
    using Microsoft.Data.Entity.Infrastructure;
    using System.Data.SqlClient;
    
    namespace Core.Data
    {
        public class DatabaseContext : DbContext, IInitialization,IDisposable
        {
            private static DatabaseContext _instance;
            
            public string ConnectionString { get; private set; }
            
            public static DatabaseContext context
            {
                get
                {
                    if (_instance == null)
                        _instance = new DatabaseContext();
                    return _instance;
                }
            }
    
            private DatabaseContext() { }
    
    #if Debug
            public void Initialize(string[] paramList)
            {
                if (paramList.IsNullOrEmpty())
                    throw new ArgumentException("Database connection string must be passed to initialize");
    
                if (paramList.Length > 1)
                    throw new ArgumentException("The only parameter required to initialize is a database connection string");
    
                this.ConnectionString = paramList[0];
            
                // Initialize "context" object here if required!
            }
    #else
            public void Initialize(string[] paramList)
            {
                //if (paramList.IsNullOrEmpty())
                //    throw new ArgumentException("Database connection string must be passed to initialize");
    
                //if (paramList.Length > 1)
                //    throw new ArgumentException("The only parameter required to initialize is a database connection string");
                //DatabaseContext.context._initializing = true;
                this.ConnectionString = paramList[0];
                
                this.Database.GetDbConnection().OpenAsync();
                DatabaseContext.context.ConnectionString = this.ConnectionString;
             
             //var s= DatabaseContext.context.Entry(avSuppliers).Context.Database.GetDbConnection();
                // Initialize "context" object here if required!
            }
    #endif
            public override void Dispose()
            {
                this.Database.CloseConnection();
                base.Dispose();
            }
           
           
          
            public virtual DbSet<Person> People { get; set; }
            public virtual DbSet<User> user { get; set; }
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Person>()
                  .HasMany(e => e.Users);
                 
                base.OnModelCreating(modelBuilder);
    
              
            }
           
            protected override void OnConfiguring(DbContextOptionsBuilder options)
            {
                options.UseSqlServer(ConnectionString);
                base.OnConfiguring(options);
            }
        }
    }
    

    Thanks,

    Ramya.

    Sunday, February 7, 2016 12:29 AM

All replies