Thursday, September 27, 2018

parent/child Code First Entity Framework relationships

Pages 171, 172, and 173 of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis touch on how to wire-up one-to-many constraints between Code First objects for Entity Framework. The de facto way to go seems to allow parent objects with collections to lazy-load the collections. They don't get loaded until first "touched" (accessed) so to speak. If a Foo has n number of Bars then the Bar POCO has an auto-property like so to tie back to its Foo like so:

[ForeignKey("FooId")]
public virtual Foo Foo { get; set; }

 
 

That's a Foo named "Foo" y'all! You will need the System.ComponentModel.DataAnnotations.Schema namespace looped in. This use of the virtual keyword blows my mind. I guess it makes both the get and the set virtual. The whole point of having getsetters (well, auto-property anymore), as best as I can tell, is to gold plate in the possibility for some polymorphism that ain't gonna happen 99 times out of 100 in flagrant disregard for the YAGNI principle. We somehow fell in love with this as developers and now having just a public variable of a specific type at a POCO seems strange while getsetters are... So Fetch! What do you do with a getsetter that does not have the virtual keyword? How do you rationalize it? I suppose it empowers method hiding distinctions from child to parent for the get and the set. I digress. Anyways, at Foo we have:

[Key]
[Required]
public int FooId { get; set; }
 
public virtual List<Bar> Bars { get; set; }

No comments:

Post a Comment