Is there an equivalent to PrepareDataContext in EF Core 2 or is this no longer required? - linq-to-sql

I am converting from LinqToSQL to Entity Framework Core 2. While converting some methods I realized I am not sure if the PrepareDataContext are required any more. I am more generally asking if there's an equivalent in EFC2. I cannot find a massive amount of information on this.
For some tangible reference here is a snippet of the code I am looking at.
Protected Overrides Sub PrepareDataContext(ByVal pobjContext As DbDataContext)
MyBase.PrepareDataContext(pobjContext)
Dim loadOptions = New System.Data.Linq.DataLoadOptions
pobjContext.LoadOptions = loadOptions
End Sub

PrepareDataContext must be a method of your own, it's not part of LINQ-to-SQL's DataContext. What matters is that the method is used to set context.LoadOptions. That's not possible/necessary in Entity Framework.
For one of its functions, LoadWith, DataLoadOptions is replaced by Include. Include is on a per-query basis, not per context, as DataLoadOptions.
For the other DataLoadOptions functions there's no direct alternative.
Side note: I assume that the code in your question is not your actual code. It wouldn't make much sense to add New System.Data.Linq.DataLoadOptions to a context without doing anything with it.

Related

Using RIO and Sqlite-net in MvvmCross

In the excellent mvvmcross-library I can use RIO binding to prevent unreadable code:
public INC<String>Title = new NC<String>();
Then I can read and write values using Title.Value. Makes the models much more readable.
Normally, this property would be written as:
private string _title;
public string Title
{
get { return _title; }
set
{
_title = value;
RaisePropertyChanged("Title");
}
}
But when I want to use sqlite-net, these fields cannot be streamed to the database because they are not basic types with a getter and setter.
I can think of a few options how to get around that:
Make a new simple object that is similar to the model, but only with
the direct db-fields. And create a simple import-export static
method on the model. This also could prevent struggling with complex
model-code that never needs to relate to the actual database.
Make sqlite-net understand reading NC-fields. I read into the code of the mapper, but it looks like this is going to be a lot of work because it relies on the getter-setter. I did not find a way to insert custom mapping to a type, that could be generic.
Remove RIO and just put in all the code myself instead of relying on RIO.
Maybe someone has some advice?
Thanks Stuart. It was exactly my thought, so I did implement it that way: my (DB) Models do not contain RIO. Only my viewmodels do, and they reference a Model that is DB-compatible.
So, for posterity the following tips:
- Do not use RIO in your models that need to be database-backed.
- Reference models in your viewmodels. In the binding you can use the . (dot) to reference this model.
This keeps them nicely separated. This gives you also another advantage: if you need to reuse a model (because the same object might be displayed twice on the screen), but under different circumstances, it is much easier to handle this situaties to find this already instantiated model.

Will manual Linq-To-Sql mapping with Expressions work?

I have this problem:
The Vehicle type derives from the EntityObject type which has the property "ID".
I think i get why L2S can't translate this into SQL- it does not know that the WHERE clause should include WHERE VehicleId == value. VehicleId btw is the PK on the table, whereas the property in the object model, as above, is "ID".
Can I even win on this with an Expression tree? Because it seems easy enough to create an Expression to pass to the SingleOrDefault method but will L2S still fail to translate it?
I'm trying to be DDD friendly so I don't want to decorate my domain model objects with ColumnAttributes etc. I am happy however to customize my L2S dbml file and add Expression helpers/whatever in my "data layer" in the hope of keeping this ORM-business far from my domain model.
Update:
I'm not using the object initialization syntax in my select statement. Like this:
private IQueryable<Vehicle> Vehicles()
{
return from vehicle in _dc
select new Vehicle() { ID = vehicle.VehicleId };
}
I'm actually using a constructor and from what I've read this will cause the above problem. This is what I'm doing:
private IQueryable<Vehicle> Vehicles()
{
return from vehicle in _dc
select new Vehicle(vehicle.VehicleId);
}
I understand that L2S can't translate the expression tree from the screen grab above because it does not know the mappings which it would usually infer from the object initialization syntax. How can I get around this? Do I need to build a Expression with the attribute bindings?
I have decided that this is not possible from further experience.
L2S simply can not create the correct WHERE clause when a parameterized ctor is used in the mapping projection. It's the initializer syntax in conventional L2S mapping projections which gives L2S the context it needs.
Short answer - use NHibernate.
Short answer: Don't.
I once tried to apply the IQueryable<.IEntity> to Linq2Sql. I got burned bad.
As you said. L2S (and EF too in this regard) doesn't know that ID is mapped to the column VehicleId. You could get around this by refactoring your Vehicle.ID to Vehicle.VehicleID. (Yes, they work if they are the same name). However I still don't recommend it.
Use L2S with the object it provided. Masking an extra layer over it while working with IQueryable ... is bad IMO (from my experience).
Otherway is to do .ToList() after you have done the select statement. This loads all the vehicles into your memory. Then you do the .Where statment against Linq 2 Object collections. Ofcourse this won't be as effecient as L2S handles all of the query and causes larger memory usage.
Long story short. Don't use Sql IQueryable with any object other than the ones it was originally designed for. It just doesn't work (well).

Transforming an object implicitly

The following code illustrates a pattern I sometimes see, whereby an object is transformed implicitly as it is passed as a parameter across a number of method calls.
var o = new MyReferenceType();
DoSomeWorkAndPossiblyModifyO(o);
DoYetMoreWorkAndPossiblyFurtherModifyO(o);
//now use o...
This feels wrong to me (it hardly feels object oriented). Is it acceptable?
Based on your method names, I would argue that there is nothing implicit in the transformation. This pattern would be acceptable. If, on the other hand your methods had names like printO(o) or compareTo(o), but actually modified the Object o, the design would be bad.
It is acceptable but usually bad style.
The usual "good" approach is:
DoSomeWorkAndModify(&o); // explicit reference means we will be accepting changes
o = DoSomeWorkAndReturnModified(o); // much more elastic because you often want to keep original.
The approach you presented makes sense when o is huge, and making a copy of it in memory is out of question, or if it's a function you (and nobody else = private) use very frequently and don't want to bother with the & syntax. Otherwise it's laziness that results in some really difficult to detect bugs.
It depends entirely on what the methods actually do, besides modifying that object.
For instance, an object primarily related to keeping some state in memory might for instance not have anything related to persisting that state anywhere.
The methods could for instance load data from a database, and update the object with that information.
However! Since I program mostly in C# and thus .NET, which is a wholly object-oriented language, I would actually write your code like this:
var o = new MyReferenceType();
SomeOtherClass.DoSomeWorkAndPossiblyModifyO(o);
SomeOtherClass.DoYetMoreWorkAndPossiblyFurtherModifyO(o);
//now use o...
In which case the actual name of that other class (or those other classes if there's 2 involved) would give me a big clue as to what is actually happening and/or the context.
Example:
Person p = new Person();
DatabaseContext.FetchAllLazilyLoadedProperties(p);
DatabaseContext.Save(p); // updates primary key property with new ID

What is the best practice/coding standard with regard to the "this" scope is AS3?

What is the best practice/coding standard with regard to the "this" scope is AS3? Is there one? I feel it really helps with standardization and my readability, but sometimes it seems like "too much".
For instance, is the use of "this" in the following really necessary (I know it works without "this")?:
private var _item:Object;
private var selectedItem:Object;
public function set item(value:Object):void
{
this._item = value;
if (this._item["label"] == "doodad")
this.selectedItem = value;
}
public function set item(value:Object):void
{
return this._item;
}
"this" is not required unless you want to prevent naming conflicts between locally scoped variables (method params for instance) and instance variables.
In your example you are already using an underscore to mark a private variable, so it's an extra reason not to use "this" since you are really saying twice the same thing.
It certainly isn't necessary, but I agree that it can help with readability. Since I work more in more dynamic languages (e.g. Perl and Python), such conventions can be vital for quickly determining where variables and functions are scoped/located. If this convention works for you, I don't think it's a bad thing, per se.
Thus said, I've spent hours reformatting code which contained awkward conventions which impeded readability.
For example: one person I worked with wrote all assignments like this:
var foo:String= "bar";
This was irritating (I prefer " = " so I can clearly see the operator), and I spent a lot of time cleaning up thousands of lines of code I had to maintain. His convention (which, though we argued about several times, he refused to compromise on) tended to impede my work.
Strive for unity w/others working with you. If they need to support your code and find this aggravating, it's likely not worth it to leave it in. If you don't expect anyone to work directly with the source, use conventions which help you understand your code and document (somewhere) what they mean.
If you're working in a team, stick with the coding conventions of the team.
But personally, I find explicit use of "this", when not required for disambiguation, overkill that negatively affects readability in a statically typed language like AS3 (dynamic languages are another story!).
A class should only really have one responsibility so generally there shouldn't be too many properties on it. Inside a method you generally deal with three types of variables: temporary local variables, method parameters, and properties. Methods shouldn't be too long, so it should be easy to spot the difference between the three types - if it's not defined locally and hasn't been passed as a parameter, then it's a property. If the whole method doesn't fit on your screen then it's probably too long!
I only use "this" when needed to disambiguate between a property and a parameter with the same name.
I prefer not to use "this" too much, but sometimes do in Eclipse, just to get autocompletion (probably the worst reason to do it!)
Would make more sense if your example was:
public function set item(_item:Object):void
{
this._item = _item;
if (this._item["label"] == "doodad")
this.selectedItem = this._item;
}

Class design: entity ID vs entity reference

If I've got Foo with a property of type Bar. Both are persisted in a database which can be retrieved by an ID. (The IDs are actually used in the line of business by customer service claims. So they're not just index placeholders.) I could take the approach shown with b1 or b2.
Chaining entities together scares me since if you push that too far, it's easy to get Null's popping up. On the other hand, having the ID show up everywhere seems like it's adding unnecessary wordiness.
int fooKey = 123;
Foo f = new Foo(fooKey);
Bar b1 = new Bar(Foo.BarID); //This?
Bar b2 = Foo.Bar; // Or This?
Note: This is NOT about the .NET Entity framework. The word entity is used here in the general sense.
As a general rule I try to avoid chaining, because it usually introduces unncessary tight coupling. All depends on the context, but in terms of business objects it might be a good idea to keep the entities loosely coupled so they can grow independently.
In the example you provide I don't think tight coupling is warranted. If the intersection was greater this might be warranted, but this isn't the general case with Business entities, I've found.
Take a look at the way MSFT implemented LINQ to SQL. They let you set either/or. Their mapper is smart enough to expose both properties and lazy-load as necessary. IMO you should go the simplest way (use an ID) or use an O/R mapper like Hibernate/NHibernate, Linq to SQL, or Linq to Entities if you want fanciness.