'One To Many Relationships With Models Not Working
So I'm trying to establish a one to many relationship between 2 models. I want to retrieve related "Collection" info for every "Member" in my controller like below:
List<Member> members = await _context.Member.ToListAsync();
My collection model (Many) is:
public class Collection
{
public int CollectionId { get; set; }
public int? MemberId { get; set; }
public DateTime? CollectionDate { get; set; }
public int? CollectionTypeId { get; set; }
public double? CheckAmount { get; set; }
public string CheckNumber { get; set; }
public double? CashAmount { get; set; }
public string CollectionDetails { get; set; }
public int? PaymentMethodId { get; set; }
public Member Member { get; set; }
}
My Member (One) class is:
public class Member
{
public int MemberId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Email { get; set; }
public DateTime? BirthDate { get; set; }
public bool? PortalUser { get; set; }
public bool? Active { get; set; }
public string ImageName { get; set; }
public string PhoneNumber { get; set; }
public int MemberTypeId { get; set; }
public int OrgId { get; set; }
public List<Collection> Collection { get; set; }
}
And my data Context:
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Collection>()
.HasOne(m => m.Member)
.WithMany(c => c.Collection)
.HasForeignKey(m => m.CollectionId);
}
public DbSet<Member> Member { get; set; }
public DbSet<Collection> Collection { get; set; }
}
But when I tried to get the data like in the controller, "Collection" comes back as null.
Failed a coding test today because of it. Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
