DbContext vs ObjectContext - navigation property behaviour change - entity-framework-6

I'm migrating a large project from ObjectContext to DbContext, EF6.1.3. Just run into an issue which will be hard to track down instances of reliably in the source code, and am wondering if there may be an approach whereby I can simulate the ObjectContext behaviour.
Consider two classes, Parent and Child. Parent has zero or more Child objects. At the table level, Child has a ParentID column which is in an FK relationship with the ID column in the Parent object. Here are the two POCO classes I generated to illustrate the issue:
Partial Public Class Parent
Public Property ID As Integer
Public Overridable Property Children As ICollection(Of Child) = New HashSet(Of Child)
End Class
Partial Public Class Child
Public Property ID As Integer
Public Property ParentID As Integer
Public Overridable Property Parent As Parent
End Class
and here is a small program to illustrate the issue:
Sub Main()
Using session As New testEntities
Dim parent = session.Parents.Add(session.Parents.Create)
Dim child = session.Children.Create
parent.Children.Add(child)
Console.WriteLine(child.Parent Is Nothing)
session.SaveChanges()
Console.WriteLine(child.Parent Is Nothing)
End Using
With an ObjectContext implementation, Adding the Child to the Parent will also set the Child's Parent property. With DbContext this doesn't happen until the session is commited.
In the code I am migrating there are several places (that we've found so far) where code will be passed the equivalent of a Child object that has been added to a Parent, then attempt to reference the Parent object through the Child's Parent property. These compile correctly, but the runtime behaviour is "broken" with DbContext.
Finding all such instances where this pattern is used will be costly and it will be very easy to miss cases that will then go on to cause problems at runtime. Can anyone suggest a workaround that will allow the code to work as is? I suppose we could modify the TT file to generate our own class instead of a HashSet for the Children property, implement a constructor that takes a reference to the dependant property, and an Add method that updates the dependent property. Before we go down that route, though, is there anything simpler that we may have missed?

I'm not entirely sure this would work, but I think it is worth a try. First, after you add the parent and children, try calling this on the DbContext:
ChangeTracker.DetectChanges()
If this results in what you want, you might be able to create your own DbSet that will call this automatically whenever Add is called... Even if you have to Shadow the Add method. (Hopefully there is just an event you can handle.)

Related

Aurelia: notification when ANY property is modified

Do you see any way to know when ANY model’s property has been modified through a binding?
I would need something generic because it would be applied to all the forms of the application. This means I cannot just have a 'property’Changed() observable callback for every properties of the models. I’m thinking along the ways of overriding the properties setters created by the binding engine so they can call a single defined callback but I feel like there could be a better way.
I created a aurelia-plugin for this kind of scenario (and more).
Its not exactly what your asking for, but can help you a lot.
because the plugin will create a single property called isDirty that you can observe and fire your code accordingly.
https://github.com/avrahamcool/aleph1-aurelia-utilities
look at the Dirty Tracking a model: section
your model class need to extends the baseClass provided by the plugin.
now you can decorate any properties of your model with the
#dirtyTrack() decorator.
for babel users: the assignment in the declaration will set the
default value for the property. for TS users: you should call the
decorator with a parameter #dirtyTrack(7) someInt: number;
this will set up a isDirty variable in your model. this property will
be automatically updated to with every change to your tracked
properties.
at any point, you can call saveChanges() on your model, to commit the
current changes. or discardChanges() to revert back to the last saved
point. you can call serialize() to get a pojo object from your model,
or deserialize(pojo) to populate your model from a pojo object.
Ok, I ended up just using the binding engine to watch all properties changes. This allowed me to implement my isDirty checks without modifying the existing models...
So the final code looks like this:
Object.getOwnPropertyNames(obj).forEach(p => {
this.subscriptions.push(this.binding.propertyObserver(obj, p)
.subscribe(() => this.updateDirty()));
});
my updateDirty() method is called after every property change and no change was necessary to the model.
If anyone can come up with a better solution, I'm still interested but this fits my needs for the time being.

Properties in nested classes in VB.NET

I keep running into the error "Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class". I'm working on a VB.NET MVC application. I have a model that has top level security Properties contained within the top level class that should be available to classes within that class. My properties always follow this structure:
Private _SecurityVar = Nothing
Public Shared Property SecurityVar
Get
If _SecurityVar = Nothing Then
_SecurityVar = User.IsInRole("SecurityFunction")
End If
Return _SecurityVar
End Get
Set(value)
End Set
End Property
My problem is is that I can't access _SecurityVar b/c it's not shared. I don't want _SecurityVar available within my view, just SecurityVar. I then need to access these top level variables from within classes that are contained within this class, such as a list of orders. I don't want to simply return User.IsInRole("SecurityFunction") because I would then be hitting the database multiple times; which would be extremely inefficient, especially when it comes to building a large table. How do I get around this, is there a better way?
Instead of sharing.. make your subclasses aware of their parentage.
In the subclass add
Private myParent as <ParentClassName>
Public Sub New(Parent as <ParentClassName>)
MyParent = Parent
End Sum
In the parent class create the subclass using
Dim Child as New <YourSubClassName>(Me)
Then when you need something from the parent in the subclass
Var = myParent.<Property Name>
If you plan on moving those subclasses around you also need to make the _Parent Public or add a method so you can change it later.
If you don't want to allow the subclass full access to the parent class you can "group" your shared variables in another class in the parent and pass that instead.
Just make your private variable shared too
Private Shared _SecurityVar = Nothing

Declaring DbContext for an MVC controller

Looking at some of the MVC examples online, I've see that typically in a controller the DbContext variable is declared as a private member variable (i.e. global) and accessible to all the methods.
But, I recently came across an article on ASP.NET Identity, and noticed in the controller, the DbContext is declared within each method (that requires it).
Is there a security benefit to this approach? Perhaps limit the lifespan of the security object(s) for better overall security?!?!
If not, then I see the first approach being more efficient, where the database context is instantiated upon the controller loading.
Below is all I could find about DbContext, but nothing to really answer my question.
DbContext declaration - Framework 4.1 - MVC 3.0
MVC, DbContext and Multithreading
On every request, a new instance of the controller is constructed. Therefore, for all intents and purposes, it does not really matter whether the dbcontext is instantiated in the constructor vs encapsulated in any given method.
Aside from a style choice, reasons to declare and contain a dbcontext in a given method is that:
Methods that do not need it will not instantiate the context, eliminating the overhead (if there is any). This can also be accomplished using a lazy initialization pattern.
The context is disposed of immediately as soon as a method is done with it, rather than at the end of the request. Generally this should not be a concern though; usually if users are waiting around for longer than a few seconds you have a bigger problem.
Different methods use different contexts.
Among others, some reasons to declare a single context and instantiate it once:
You have only one place that instantiates a context rather than many. In a typical application, most pages will need some information from the database anyway.
Methods that call other methods will not each hold on to their own instance of a context object.
You can create a base controller class that by default creates a dbcontext object, allowing you to be DRY in all inherited controllers.
Answer from #Ic. is pretty good. I wanted to add that if you need to pass information from your Request into your DbContext constructor then you need to create the instance of your DbContext inside your action methods. The reason is the Request object will be null till the control enters your action method.
More information: I had a need to build connection string dynamically depending on the location of the user. I saved the location as a cookie that I accessed through Request object. I had a valid Request inside the action method but it was null inside the constructor or at the class level properties of the controller.

The appropriateness of dependency injection

Ok, so I think that I have a basic understanding of IoC and the patterns relating to it, dependency injection and the service locator pattern.
From what I have read it seems that dependency injection into a class constructor is more favourable for loose coupling that the service locator.
What I am having trouble understanding, and can’t really find anything written about it, is what to do if I want to instantiate an object from a high level class? Do I have the change the constructor for the class which is calling the new class? If so, that would mean that I would have to change the every call to that constructor and the constructors of every class making that call, and so to the root. This seems very cumbersome and unsafe. Would a service locator be more appropriate in this scenario?
Any advice would be appreciated.
Simple example:
class car
void car(iBrand brand, iModel model){
_brand=brand;
_model=model;
}
class brand : iBrand
void brand (iModel model){
_model=model;
}
class model : iModel
void model()
This is a particularly crude example but hopefully should get my point across. each of these objects instantiates the class below. Now if I want to create an iEngine in the model class, does this mean it has to be passed all the way down from the top, including into the car constructor?
class car
void car(iBrand brand, iModel model, iEngine engine){
_brand=brand;
_model=model;
_engine=engine;
}
Thanks,
H
There should be only one place in your application that is instantiating injectable classes; the Composition Root. So there should be nobody but the Composition Root who is calling the components' constructors. It should be the Composition Root who composes the object graphs.
A dependency should only be included in the constructor of a type, if that type uses that dependency directly. In your example both Brand and Car depend on IModel, but if Car doesn't need to interact with IModel directly, model should not be injected into Car. Or imagine a UsersController class that depends on an IUserRepository. If the UserRepository needs to be extended with some logging, the UsersController should not have to know about this. You should just inject an ILogger into the UserRepository's constructor and the UsersController stays unaffected.
Since the Composition Root is the only place that calls the constructor, and adding dependencies should not ripple through the whole dependency graph, changing a constructor should mean that only the Composition Root is affected (besides the class in question of course). And if you use a DI framework, you will in most cases even prevent having to change anything at all.

How to define create method for intermediate class during in mapping in Dozer

Here's my scenario, I have 2 classes "com.project.ClassA" and "com.project.ClassB", I'm trying to map the fields ClassA.name to ClassB.person.nameObj.firstName.
As you can see, Dozer needs to create person object and nameObj before it can do the mapping, there is some factory classes to initiate the Person and NameObj objects.
I know we can define custom create method in field and class level, but that only applies to the field or the class that you are mapping. In my example, the mapping are between 2 String fields, but 2 objects are required to be created before the mapping is performed.
The error I'm getting now is
org.dozer.MappingException: java.lang.NoSuchMethodException: com.project.ClassB.Person.()
Any helps or ideas will greatly appreciated. Thanks.
Two things
1. ClassB needs a constructor which initialized obj Person, similarly Person needs a constructor to initialize nameobj.
2. accessor and mutator methods should be present (getters and setters).
After you do both these steps this should work.

Resources