Answer the question
In order to leave comments, you need to log in
How to get data cascading from the database?
Hello there are two related classes - entity
User
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; }
}
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>();
}
}
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();
}
}
User user = db.User.FirstOrDefault(x => x.Name == name);
if (user == null) {
// to do something
}
if (user.Company == null) {
// <- Company null хотя не должен быть.
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question