How does EF Core instantiate and initialize entities? - entity-framework-core

How does EF Core instantiate and initialize objects that are retrieved from a database? In the following example, the Person class has a default constructor and a parameterized constructor. Neither of these constructors is called when my program retrieves the Person object from the database.
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person()
{
Console.WriteLine("Default ctor accessed");
}
public Person(string firstName, string lastName)
{
Console.WriteLine("Parameterized ctor accessed");
FirstName = firstName;
LastName = lastName;
}
}
// Program.cs
// Other code omitted for brevity
var personRead = context.Persons.First(p => p.FirstName.Equals("MyName"));
Console.WriteLine($"Firstname: {personRead.FirstName}");
This conflicts with the microsoft documentation:
When EF Core creates instances of these types, such as for the results of a query, it will first call the default parameterless constructor and then set each property to the value from the database. However, if EF Core finds a parameterized constructor with parameter names and types that match those of mapped properties, then it will instead call the parameterized constructor with values for those properties and will not set each property explicitly
The article was written on 14/10/2020 so it might be out of date. However my question still remains. How does EF core instantiate and initialize these objects? I'm using Microsoft.EntityFrameworkCore version 6.0.8

Neither of these constructors is called when my program retrieves the Person object from the database
This can't be true except you have another constructor(s) not shown here.
EF Core definitely uses class constructor for instantiating entities, so the documentation is correct, however it's unclear which one in case there are multiple. All it says is:
Note
Currently, all constructor binding is by convention. Configuration of specific constructors to use is planned for a future release.
The answer is hidden inside the implementation of the ConstructorBindingFactory class which is responsible for selecting the constructor to be used, and more specifically the following comment inside GetBindings method:
Trying to find the constructor with the most service properties
followed by the least scalar property parameters
Service properties are explained in Injecting services section, and scalar property parameters refer to primitive type constructor arguments explained in Binding to mapped properties.
In your example, there is no constructor with service type arguments, so the one with the least scalar property parameters will be chosen, which in this case is the parameterless constructor (parameters count is 0)
public Person()
{
Console.WriteLine("Default ctor accessed");
}
Again, if you have other constructors, check if some of them is "better". But as it looks, if you have parameterless constructor (doesn't matter if public, protected, internal, private etc.) and no constructors with service type arguments, then EF Core will always use the parameterless one.
If you want, you can check the entity instantiation info using the metadata API, e.g.
var entityType = dbContext.Model.FindEntityType(typeof(Person));
var info = entityType.ConstructorBinding;
ConstructorBinding property returns instance of abstract type InstantiationBinding class. ParameterBindings property returns information about parameters and corresponding properties, and CreateConstructorExpression method which
Creates an expression tree that represents creating an entity instance from the given binding information. For example, this might be a NewExpression to call a constructor, or a MethodCallExpression to call a factory method.
Currently there are two implementations of aforementioned abstract type - ConstructorBinding class for instantiation using constructor, and FactoryMethodBinding class for instantiation via factory method.
So, currently by convention EF Core uses constructor instantiation, but factory method instantiation might be added in the future (it might even be used currently by proxies extension, but it uses/requires parameterless constructor in the class they are inheriting).

Related

Why does nesting a class give the containing class access to the child class' protected data?

The question may be a bit confusing, and is best illustrated by an example:
unit Test
interface
type
TestClass = class()
Splitter1: TcxSplitter;
procedure SomeMethod();
end;
implementation
uses
cxSplitter;
// Locally-declared child type
type
TcxSplitterAccess = class(TcxSplitter);
procedure TestClass.SomeMethod()
var
pos: integer;
begin
// Access to protected field FPositionBeforeClose by casting
pos := TcxSplitterAccess(Splitter1).FPositionBeforeClose;
end;
Notice in the implementation section that there is a type TcxSplitterAccess being declared as a child of the TcxSplitter class. In the method SomeMethod(), belonging to the class TestClass, a TcxSplitter object is cast to the locally-declared TcxSplitterAccess class, and then a protected field is accessed on that object.
This is surprising to me as someone coming from a background of languages like Java, C++, C#, etc. In those languages, it is possible to access protected data in an object so long as you are doing it from within that object's type or an inherited type. For example, a method inside of a class ClazzA can access the private fields of other ClazzA objects since access is enforced at the type level rather than the instance level. Declaring a class locally in these languages would not give the containing class access to the local class' protected data (edit: As pointed out in the comments, this is actually not true at least for Java).
In this example, however, the type TestClass is directly accessing a protected field on the TcxSplitter object by first casting to the TcxSplitterAccess type. I am having trouble finding documentation on why this "trick" works. Does Delphi handle access levels fundamentally differently to Java-like languages and allows this sort of thing? Regardless, why does this trick work?
While I stumbled onto this behavior by using a nested, inherited class in order to access fields on the parent class (which breaks encapsulation, and I shouldn't do), the use of inheritance here is unnecessary. If the nested class did not inherit from a class, but instead had its own protected fields defined, TestClass would still be able to access those protected fields.
A unit has implicit-friendship semantics within itself. Types declared in the same unit are "friends" of each other (similar to friend in C++), and so can access each other's private and protected members (but not strict private or strict protected members).
So, in this case:
TcxSplitterAccess derives from TcxSplitter, so TcxSplitterAccess inherits all of the protected (but not private) members of TcxSplitter via normal class inheritance.
TestClass is declared in the same unit as TcxSplitterAccess, so TestClass has access to all of the protected members of TcxSplitterAccess, including the protected members of TcxSplitter (and the protected members of its ancestors).
FPositionBeforeClose is protected in TcxSplitter.
So, that is why TestClass.SomeMethod() is able to access FPositionBeforeClose when type-casting the Splitter1 object to TcxSplitterAccess.
This is covered by the Delphi documentation:
Private, Protected, Public, and Published Declarations
Classes and Objects (Delphi): Visibility of Class Members

Property cannot be declared public because its type uses an internal type

I created two classes Content and Bucket. Bucket contains an array of Content objects and exposes that via a public property. However, when I do so, I receive the error:
Property cannot be declared public because its type uses an internal type
Any thoughts on why this is raising an error?
You have to declare the access level of the Content class public as well.
public class Content {
// some code
}
As stated in the documentation:
A public variable cannot be defined as having an internal or private
type, because the type might not be available everywhere that the
public variable is used.
Classes are declared as internal by default, so you have to add the public keyword to make them public.
A similar rule exists for functions as well.
A function cannot have a higher access level than its parameter types
and return type, because the function could be used in situations
where its constituent types are not available to the surrounding code.
Content must be declared as public too:
public class Content {
…
}
Depending on your use-case you might declare Bucket as internal, too. Just omit the public keyword in this case.
My issue was a namespace problem.
I had declared an enum called Data and that was mucking with the Swift Data class, especially an imageData: Data property within a Core Data model.

Interface Injection chapter in DI

I just start learning what is Dependency Injection and InversionOfControll is. But I cant get one thing. The interface injection is onle when I define some interface where describe method what need to be realized. And that method gets instance of some class as parameter, and then In class what implements interface just describe body of this method ?
An interface is only a contract that defines what public members a class should implement. It does not control the actual implementation - you need a concrete class to do that.
// This is only a contract that defines what members
// all concrete types must implement.
public interface ISomeType
{
void DoSomething();
}
// This class implements the interface. Therefore, it must
// have all of the methods the contract specifies. In some
// languages, this can be done implicitly just by adding the
// member, but it usually must be public.
public class SomeType : ISomeType
{
public void DoSomething()
{
Console.WriteLine("Hello World");
}
}
When you make a class implement an interface it implicitly means that instances of the class can be cast to the interface type.
ISomeType x = new SomeType();
Dependency Injection takes advantage of this behavior. You typically define both the interface type and the concrete implementation together in a mapping.
container.For<ISomeType>().Use<SomeType>();
Then when a service is declared to take ISomeType as a constructor argument, the map is used to determine which concrete type to create an instance of.
public class SomeService : ISomeService
{
private readonly ISomeType someType;
public SomeService(ISomeType someType)
{
if (someType == null) throw new ArgumentNullException("someType");
this.someType = someType;
}
}
The recommended way is to allow the DI container to do this implicitly when your entire object graph is composed (in the Composition Root), but it is possible also to do it explicitly (and it makes a better example):
ISomeService = container.GetInstance<ISomeService>();
Assuming that the container was configured to map ISomeService to SomeService (like I showed before with ISomeType), this one line of code will create an instance of SomeService and automatically inject an instance of SomeType into its constructor.
It is difficult to see the point in a simple example, though. Dependency Injection is meant for complex applications with many types. It simplifies things when the application is complex, but when the application is simple it has a tendency to make things more complex.

Injecting with Gin into instance created by GWT.create

I have a custom deferred binder (rebind implementation) that instantiates objects. I would like to have some dependencies (#Inject annotated setter methods) within the instance returned by GWT.create() fulfilled by GIN. Is this possible?
So, given code such as:
Foo foo = GWT.create(Foo.class);
if foo's final implementation has:
#Inject
public void setBar(Bar bar) {
...
}
how do I get bar injected into the returned foo instance automatically by GIN?
Your Ginjector can have methods added to it for the purpose of injecting objects created in some other way. These must take one argument, and should specify the most specific type possible. For example, if MyViewImpl extends BaseView, and both types have dependencies to inject, but you declare
void injectBaseView(BaseView view);
in your ginjector, only the fields/setters declared on BaseView will be dealt with.
EDIT: Also, if no binding is declared, GWT.create will be used to create an instance, so you can have your cake and eat it to. One exception to that as far as I can recall, is when you want to GWT.create one type, but return another (see RPC interfaces for an example).

Generic Wrapper Class possible?

On C# 3.0 and .NET 3.5, imagine there's an interface:
public interface INameable
{
string Name {get;}
}
and many immutable classes that implement the interface.
I would like to have a single extension method
public static T Rename<T>(this T obj) where T : INameable
{
...
}
that returns a wrapped instance of the original object with just the name changed and all other property reads and method calls routed to the original object.
How to get a generic wrapper class for this, without implementing it for all INameable implementing types? Do you think that's possible?
No, this isn't possible, unless T is constrained to be an interface or to be a class with all members virtual, and this constraint isn't possible to specify at compile time (though you could write a runtime check if you're happy with that approach).
The reason you cannot do it for arbitrary types is that if you take an object of type T then you must return an object that is assignable to T. If I pass an object that looks as follows...
public sealed class SomeClass : INameable
{
public string Name { get; }
public string Abc { get; }
}
...then there is no way you can create another type that is assignable to SomeClass. Not using Reflection.Emit or any other method, because the type is sealed.
However, if you're happy with the restrictions that I've mentioned then you could use something like the Castle DynamicProxy framework to create a type that proxies the passed in object and intercepts the calls to either forward or re-implement as appropriate.
Well, yes, it's possible, but it involves generating code in memory.
You can look at Reflection.Emit and here.
Note that it will involve a lot of code.
That is, if I assume I understand you correctly.
Here's what I think you're asking for:
SomeNameableObject a1 = new SomeNameableObject("ThisIsTheFirstName");
SomeNameableObject a2 = a1.Rename("ThisIsTheSecondName");
// a1 works, still has the name ThisIsTheFirstName
// a2 works, but everything is routed to a1,
// except for the name, which is ThisIsTheSecondName
Is that correct?