0

Im new to c# and Im working on a entity framework project that access a mysql database and has two models: User and Company.

the problem is, when making the connection everything is okay with the database connection, the model gets all of user's info, even companyId, but the other company properties such as companyName comes back as null and accountType as 0.

I dont know where the problem could be. User looks like this:

public partial class user
    {
        public user()
        {
            this.company = new company();
            
        }


public System.Guid userId { get; set; }
public System.Guid companyId { get; set; } //this is my fk
public string username { get; set; }

public virtual company company { get; set; }
public string companyName => company?.Name;
public int AccountType => company?.AccountType ?? 5;

}

and my company class looks like this:

public partial class company
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public organization()
    {
        this.users = new HashSet<user>();
    }
    public System.Guid companyId { get; set;}



     public string Name { get; set; }
        public string Address { get; set; }
        public int AccountType { get; set; }
System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<user> users { get; set; }
}

my onModelCreating method:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<user>()
                .HasRequired(u => u.company)
                .WithMany(c => c.users)
                .HasForeignKey(u => u.companyId);
        }



    
vitoriac
  • 79
  • 1
  • 1
  • 7

1 Answers1

0

EF will not load relationships by default, you need to use one of the approaches to load related data. Personally I usually prefer eager loading, for example:

var user = dbContext.Users
   .Include(u => u.company)
   .FirstOrDefault(u => u.userId == someId);

Also you can configure auto-include:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // ...

    modelBuilder.Entity<user>().Navigation(e => e.company).AutoInclude();
}

P.S.

Consider following recommended C# Coding Conventions (like classes and properties names using PascalCasing i.e. user -> User)

Guru Stron
  • 102,774
  • 10
  • 95
  • 132