G
G
Georgy Pugachev2021-02-19 17:37:10
C++ / C#
Georgy Pugachev, 2021-02-19 17:37:10

How to get data cascading from the database?

Hello there are two related classes - entity
User

Source

public class User {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        [Required]
        public Guid Guid { get; set; }
        [Required]
        public string Name { get; set; }

        [ForeignKey("Company")]
        public Guid? CompanyGuid { get; set; }
        public virtual Company Company { get; set; }
}


company
Source

public class Company {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Required]
    public Guid Guid { get; set; }
    [Required]
    public string Name { get; set; }

    public virtual ICollection<User> Users { get; set; }

    public Company() {
        Users = new List<User>();
    }
}



Their Context
Source

public class CompanyContext : DbContext
    {
       public CompanyContext (DbContextOptions<CompanyContext> options) : base(options) {
        }

        public DbSet<Company> Company { get; set; }
        public DbSet<User> User { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            modelBuilder.Entity<User>()
                .HasOne(p => p.Company)
                .WithMany(b => b.Users)
                .HasForeignKey(p => p.CompanyGuid);

            modelBuilder.Entity<Company>()
                .HasMany(b => b.Users)
                .WithOne();
        }
    }


Everything is created correctly in the database, Foreign key is present. The data is also present in the database.
But when executing the following code, I get User.Company = null
Source

User user = db.User.FirstOrDefault(x => x.Name == name);
if (user == null) {
    // to do something
}

if (user.Company == null) {
    // <- Company null хотя не должен быть.
}



Please tell me what I'm doing wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaratFakhrutdinov, 2021-02-19
@gvpugachev

You need to add a navigation property to the Include. The Entity Framework will generate a Join for you and translate the required columns into the Company object by assigning it to the corresponding property.

User user = db.User
.Where(u => u.Name == name)
.Include(u => u.Company)
.FirstOrDefault();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question