Switches for LazyLoading with Repository pattern - c#

By default LazyLoading is disabled in my DbContext. I use repository pattern and in some case I need to get only simple object and in other I need to get object with values of navigations properties.
How can I implement something like switches for LazyLoading?
Any help will be appreciated
I have one solution that works but I'm not sure that it is correct:
in interface of repository I added new property
public interface IRepository<T> where T : BaseEntity
{
T GetById(object id);
void Insert(T entity);
.....
bool LazyLoadingSwitches { set; }
}
Then implemented it:
public bool LazyLoadingSwitches
{
set
{
this.context.Configuration.LazyLoadingEnabled = value;
}
}
and when I need to get model with related data then I use in controller:
repository.LazyLoadingSwitches = true;
name = order.Customer.FullName;
repository.LazyLoadingSwitches = false;
Please suggest me what is the best solution for that?

Just my two cents:
I think implementing a wrapper around the this.context.Configuration.LazyLoadingEnabled = value; call is OK. I would implement it as a method though, a write only property is quite odd.
In my coding I let the code that executes the query decide if it wants to use lazy loading or .Include statements. Most important is that the code that is going to consume the class that was returned finds all data in it that is needs.

I think you can use include:
order.Include("Customer");
var name = order.Customer.FullName;
Sample with lambda expression:
order.Include(o => o.Customer);
var name = order.Customer.FullName;

Related

asp.net Generic repository find by property

I am using Generic Repositories with ASP.NET. Now I am trying to find an object by the user Id which requires to access a property of the class, but ofcourse in the linq expression the property is not know, because it does not know the type yet. Is there any way around this?
public virtual IEnumerable<T> GetByUser(string userId)
{
if (typeof(T).GetProperty("Employee") != null)
{
return Db.Set<T>().Where(x => x.Employee.Id == userId);
}
return new List<T>();
}
the "x.Employee.Id" gets the error that there is no definition of Employee. That is to be expected. Do I need to do this in an entire different way or does somebody knows how to fix this?
I hope anybody can help!
Use interfaces so that you know T will have certain properties. Or use a base type and then use constraints on the generic parameter.
public virtual IEnumerable<T> GetByUser(string userId) where T : IEmployee
{
return Db.Set<T>().Where(x => x.Employee.Id == userId);
}
And where IEmployee looks like this
public interface IEmployee
{
Employee Employee { get; set; }
}
Obviously this is a bit crude, but depending on your entities this could be an approach. You could always map out everything and then build up your interfaces for the shared properties etc.
However to be honest I think your best approach is to have a more functional set of generic repositories. For example a base repo, and then an EmployeeRepostiory that knows that T will be an Employee.
MSDN Article on Constraints

Need to perform actions on EF objects with common fields, not sure if/how I need to use Interfaces

I'm using Entity Framework. I have a few database tables that store different statistics:
Stats1 (Stats1ID, Mean)
Stats2 (Stats2ID, Mean)
Stats3 (Stats3ID, Mean)
I have multiple methods which I want to consolidate into a single method. The only difference between these methods are the parameters:
public static bool IsValid(Stats1 stat, decimal value) { // }
public static bool IsValid(Stats2 stat, decimal value) { // }
// etc
The methods all use the common field of these different Stat objects - 'Mean'. How do I replace the first parameter with some generic object that I can use to access the Mean field of whichever type is passed in? Not sure if this is relevant but I use "database first" and generate the model like that
edit: appreciate the answers, will test things soon
All Stats classes can implement an interface, say IStat, containing the Mean property. It's enough to extend a generated partial class by another partial class:
partial class Stats1 : IStat { }
EF doesn't mind, as long as you don't use the interface for navigation property types (but you won't with database first).
Then you can define a generic method with a generic type constraint (where):
public static bool IsValid<T>(T stat, decimal value)
where T : IStat
{
// Example of what you could do here:
return stat.Mean > value);
}
Usage:
var valid = IsValid(stat1, 1);
EDIT - Didn't notice you're using Database First. I use this approach in code first, and it probably don't apply to you. But I leave it here in case anyone reads the question later.
You can define an interface that denoted the common field, like:
public interface IStatEntity
{
public int Mean { get; set; }
}
and implement the interface on all of the entities. Implementing an interface does not interfere with EF's mappings and doesn't mean anything to EF.
I use the same approach for having properties such as CreationTime and LastModificationTime and then setting them centrally in my DbContext.
You could use reflection to do what you want.
public static bool IsValid<TStats>(TStats stats, decimal value)
{
if (Equals(stats, null))
return false;
// Get the 'Mean' property
var propertyInfo = typeof(TStats).GetProperty("Mean");
if (Equals(propertyInfo, null))
return false;
// Get
var meanValue = propertyInfo.GetValue(stats, null) as decimal?;
// ... do what ever you want with the meanValue
return meanValue.HasValue && meanValue.Value == value;
}

Effects of returning a self reference from an instance method in C#

Let's say I have an interface called IConvertableModel and it helps me to convert some MVC models to/from DTO objects as shown below:
public class DisplayEditModel : IConvertableModel<Display>
{
[HiddenInput(DisplayValue = false)]
public int ObjectId { get; set; }
[StringLength(255)]
public string Description { get; set; }
public Display ToDto()
{
return new Display
{
Description = Description,
ObjectId = ObjectId,
};
}
public void SetFromDto(Display dto)
{
Description = dto.Description;
ObjectId = dto.ObjectId;
}
}
But there is one problem with this approach and that is it doesn't allow me do this :
var dto = _dtoRepository.GetFirstDto();
return new DisplayEditModel().SetFromDto(dto);
Instead I should do the following:
var dto = _dtoRepository.GetFirstDto();
var model = new DisplayEditModel();
model.SetFromDto(dto);
return model;
and this is adding extra two lines of code and little bit complexity in the long run.
What I am thinking is to convert SetFromDto method to something like this:
public DisplayEditModel SetFromDto(Display dto)
{
Description = dto.Description;
ObjectId = dto.ObjectId;
return this;
}
I think the benefit of this code is obvious but I also like to learn whether this harms code readability and leads to unexpected results for developers in the long run and if you think anything else, what would you recommend.
Note: Because of the interfaces reasons, I am not thinking to implement a constructor method.
A few thoughts, to begin with:
Adding lines of code is not the same as adding complexity. Having three statements, where each does a simple operation, is not necessarily harder to maintain or understand than a single statement with three operations inside of it.
When a method that begins with Set..., programmers will automatically assume that some stateful values of the target object are going to be changed by this method. It is rare for Set methods to have a return value. Property setters in C# actually "return" the original value passed into them, so you can chain setters:
int i = foo.A = 2;
So the precedent is generally against returning "this" from a set method specifically.
Chaining in general is most useful/desired when you're expecting several operations to be performed, one after the other. For example, C# provides nice initialization syntax so you can "chain" a bunch of different property setters on the same object:
var foo = new Foo { A = 1, B = 2 };
You can see how chaining is fulfilling the need to perform similar, grouped, repetitive operations that typically get performed all together. That is not the problem that you are trying to solve.
If your main gripe is that you don't like having three lines of code, why not just use a helper whose name indicates what you're trying to do?
TModel MapToModel<TModel, TDto>(TDto dto, TModel model)
where TModel : IConvertableModel<TDto>
{
model.SetFromDto(dto);
return model;
}
// usage:
var dto = _dtoRepository.GetFirstDto();
return MapToModel(dto, new DisplayEditModel());
... or even:
TModel CreateModel<TModel, TDto>(TDto dto)
where TModel : IConvertableModel<TDto>, new()
{
var model = new TModel();
return MapToModel(dto, model);
}
// usage:
var dto = _dtoRepository.GetFirstDto();
return CreateModel<DisplayEditModel>(dto);
This is simple, readable, and feasible, whereas the approach you're suggesting would break the IConvertableModel<Display> interface:
public interface IConvertableModel<TDto>
{
public TDto ToDto();
public ??? SetFromDto(TDto dto);
}
What would SetFromDto return? You would have to define another generic type on IConvertableModel.
public interface IConvertableModel<TDto, TModel> {
public TDto ToDto();
public TModel SetFromDto(TDto dto);
}
But this wouldn't really indicate that the SetFromDto method is necessarily returning itself, because it allows for a class that is not a TModel to implement IConvertableModel to convert between two other types.
Now, you could go out of your way to push the generics even farther:
public interface IConvertableModel<TDto, TModel>
where TModel : IConvertableModel<TDto, TModel>
{...}
But this still allows for some fudging, and the interface cannot guarantee that you are really returning "this" object. All in all, I'm not a big fan of that approach.
Rather than having DisplayEditModel have a get/set method for a Display object to get/set the values, just use a property that doesn't actually have a separate backing store:
public Display Display
{
get
{
return new Display
{
Description = Description,
ObjectId = ObjectId,
};
}
set
{
Description = value.Description;
ObjectId = value.ObjectId;
}
}
Now you can use an object initializer with this property when creating a model:
return new DisplayEditModel() { Display = dto };
This is a very javascript way of approaching this problem, though it has it's benefits. In the context of C#, it is a little bit strange though libraries such as LINQ do this to allow chaining together function calls.
My only worry about this, is that this has to be a class that does this consistently. Implementing a chaining function return pattern is not really a convenience as much as it is a design choice. The rule to follow in this case, would be to return this every time you mutate the object.
Chaining also may not be worth it performance wise. Something that can be done by wrapping all those operations into a single function is much faster. For instance:
MyVector.setX(1).SetY(1).SetZ(1).SetW(0)
is a lot slower than simply
MyVector.set(1, 1, 1, 0)
because now you are now doing excessive stack operations to do something fairly simple. It only becomes worth it on very large operations that take up the bulk of the computing time and make sense to chain together. For this reason, LINQ allows you to chain things together.
I wouldn't say that it necessary "harms" or is dangerous. We are in the world of a managed language, so we don't have direct access to that memory location (unlike C/C++). So I would just call it a design choice which can be fairly powerful in some cases and not so much in others.
As noted, chainable methods work fine but are not as common in C# as in some other languages. If the extra lines of code only happen in one place, I'd just leave it alone. If it's really bugging you or you do it a lot, then consider implementing a special constructor for it:
public void DisplayEditModel(Display dto)
{
this.SetFrom(dto);
}
or a static factory method:
public static DisplayEditModel CreateFrom(Display dto)
{
var model = new DisplayEditModel();
model.SetFrom(dto);
return model;
}
Either option has a clear intent, lets you create and return the object in a single line, and is idiomatic. It does require a few extra lines of code in DisplayEditModel, but I doubt it will be a serious problem.

Delegated - is correct my usage of delegates?

I created a class where the main task is get data from the DB and mapping it to some object. The problem is the same class needs to map different datareader to different object. So, what I tried to do is to get out the mapping method using delegates.
Here is part of my code. See the important rows in bold.
public class GetDetails<T>
{
**public delegate void DelegateMapping(T position, IDataReader reader);**
**public DelegateMapping mappingMethod;**
public T Get(T instance)
{
//Get IDs and Add to list
_db.ExecuteReader(storedProcedure.ToString(), CommandType.StoredProcedure, reader =>
{
while ( reader.Read() )
{
**mappingMethod(instance, reader);**
}
}, parameterList.ToArray());
return instance;
}
}
And this is the class which is calling and using the "GetDetails" class
public class PositionDB : DbBase
{
public Position GetPositionDetails(string IDs)
{
GetDetails<Position> getIDs = new GetDetails<Position>(base.db);
getIDs.storedProcedure = StoredProcedure.NET_ADM_GetPositionDetails;
//Set the Delegated Method
**getIDs.mappingMethod = MappingPositionDetails;**
//Set Parameters
getIDs.parameterList.AddInParam("PositionIds", DbType.String, IDs);
//Return the PositionId Collection
return getIDs.Get(new Position());
}
**private void MappingPositionDetails(Position position, IDataReader reader)
{
position.Id = reader["CompPositionId"];
position.Description = reader["Description"];
position.ExpirationDate = reader["ExpirationDate"];
position.Title = reader["Title"];
}**
}
The code is working OK.
The questios are:
Did I use delegate correctly?
This kind of solution can cause problems in the future (performance)?
There is another better solution?
Thank you very much
Sebastian
To specifically answer your questions:
Yes, you did use delegates correctly
Yes, it can cause problems due to concurrency issues while multithreading
I think so, I detailed one possible solution below
I would propose three changes:
Move the delegate call into the method (concurrency issues, one thread could change the mapping delegate while another thread tries to access it, now trying to map a reader to completely different object than provided)
Use the already present generic Action/Func delegates, no need to define your own.
Use lambda expressions to define the mapping, no need for extra methods
Notice: 2 and 3 will need at least .net 3.5.
Employing these two proposals, your code would look like this:
public class GetDetails<T>
{
public T Get (T instance, Action<T, IDataReader> mappingMethod)
{
//Get IDs and Add to list
_db.ExecuteReader(storedProcedure.ToString(), CommandType.StoredProcedure, reader =>
{
while ( reader.Read() )
{
mappingMethod(instance, reader);
}
}, parameterList.ToArray());
return instance;
}
}
Now you can use this method in a multi-threaded environment as well.
Edit
just realized it's just part of the code. I corrected my proposal to take this into account.
Yes (There's some improvements you could make, see 3)
Not performance wise, maybe some issues in discoverability.
I would use polymorphism to eliminate the delegate completely for discoerability. Perhaps using an abstract method/class. Also depending on which .NET version you're developing for you can use lambdas and simpler types.
public Action<Position, IDataReader> Mapping { get; set; }
Then
getIDs.Mapping = (position, reader) =>
{
position.Id = reader["CompPositionId"];
position.Description = reader["Description"];
position.ExpirationDate = reader["ExpirationDate"];
position.Title = reader["Title"];
};

Design Patterns Recommendation for Filtering Option

I am thinking to create a filter object which filters and delete everything like html tags from a context. But I want it to be independent which means the design pattern I can apply will help me to add more filters in the future without effecting the current codes. I thought Abstract Factory but it seems it ain't gonna work out the way I want. So maybe builder but it looks same. I don't know I am kinda confused, some one please recommend me a design pattern which can solve my problem but before that let me elaborate the problem a little bit.
Lets say I have a class which has Description field or property what ever. And I need filters which remove the things I want from this Description property. So whenever I apply the filter I can add more filter in underlying tier. So instead of re-touching the Description field, I can easily add more filters and all the filters will run for Description field and delete whatever they are supposed to delete from the Description context.
I hope I could describe my problem. I think some of you ran into the same situation before.
Thanks in advance...
Edit :
I actually want to create filters as types/classes instead of regular methods or whatever. Like :
class TextFilter : IFilter
{
private string something;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class HtmlFilter : IFilter
{
private string something;
private string iGotSomething;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class Main
{
protected void Main(object sender, EventArgs e)
{
InputClass input = new InputClass();
string filtered = new StartFiltering().Filter(input.Description); // at this moment, my input class shouldn't know anything about filters or something. I don't know if it makes any sense but this is what in my mind.
}
}
At this point if I want to apply Abstract Factory which would be meaningless or Builder as well. Because I don't want a particular thing, I need all of them kinda.
Thanks for your answers by the way.
Edit 2 - Possible Answer for Me
Okay lets think about strategy pattern with interfaces rather than delegates.
interface IFilter //Strategy interface
{
string Filter(string text);
}
class LinkFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter link tags and return pure text;
}
}
class PictureFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter links and return pure text;
}
}
class Context
{
private IFilter _filter;
private string _text;
public Context(IFilter filter,string text)
{
this._filter = filter;
this._text = text;
}
public void UpdateFilter(IFilter filter)
{
this._filter = filter;
}
public string RunFilter()
{
this._text = _filter.Filter(this._text);
return this._text;
}
}
class MainProgram
{
static void Main()
{
MyObject obj = new MyObject();
LinkFilter lfilter = new LinkFilter();
PictureFilter pfilter = new PictureFilter();
Context con = new Context(lfilter,obj.Description);
string desc = con.RunFilter();
con.UpdateFilter(pfilter);
desc = con.RunFilter();
}
}
Why don't you just go light weight: Define your filter as a Func<string, string>. If you keep these in a collection (List<Func<string, string>>), you can just do:
var text = myObject.DescriptionProperty
foreach (var func in myFuncList)
{
text = func(text);
}
You can also use Linq to shorten the above loop:
var text = myFuncList.Aggregate(text, (seed, func) => func(seed));
This way, you don't have to define a class hierarchy for filtering. This is good for the environment, since we will be running out of classes and namespaces very soon!
To wrap things up, I suggest you subclass List:
public class FilterCollection : List<Func<string, string>>
{
public string Filter(string text)
{
return this.Aggregate(text, (seed, func) => func(seed));
}
}
Have you looked at the strategy pattern? It allows you to swap algorithms.
If that is not what you are looking for, perhaps the decorator pattern will be more suitable. This will allow you to wrap filters and apply multiple ones if needed.
To me this sounds like the Strategy pattern.
Could be something like this (the code is in VB):
Function GetFilteredDescription(ByVal iSpecificFilterFunction As AbstractFilterFunction) As Result
Return iSpecificFilterFunction.Filter(Me.description)
End Function
Note: the GetFilteredDescription is member function of your class.
You can use below patterns:
Strategy Pattern for different Filter types
Chain of Responsibility for your filter stack (You can add Command Pattern here for different chains in a multitasking environment, or you can implement priority based chain or so on )
Builder or Abstract Factory for Filter instance creations.
What about Provider pattern? http://msdn.microsoft.com/en-us/library/ms972319.aspx
It is similar to Strategy, and is used in Microsoft products thoroughly.

Categories