LINQ to SQL repository - caching data - asp.net

I have built my first MVC solution and used the repository pattern for retrieving/inserting/updating my database.
I am now in the process of refactoring and I've noticed that a lot of (in fact all) the methods within my repository are hitting the database everytime. This seems overkill and what I'd ideally like is to do is 'cache' the main data object e.g. 'GetAllAdverts' from the database and to then query against this cached object for things like 'FindAdvert(id), AddAdvert(), DeleteAdvert() etc..'
I'd also need to consider updating/deleting/adding records to this cache object and the database.
What is the best apporoach for something like this?
My knowledge of this type of things is minimal and really looking for advice/guidance/tutorial to point me in the right direction.
Thanks in advance.

This just hit my radar, and I assume you have already solved the issue by now. But if not, I would look into Pre-Compiled LINQ Queries. Something like this:
private static Func<SomeDataContext, int, PersonDto> _getPersonByIdQuery =
CompiledQuery.Compile<SomeDataContext, int, PersonDto>(
(dataContext, personId) =>
dataContext.PersonDtos.where(c => c.PersonId == personId).FirstOrDefault()
);
Put something like that inside of your datacontext, then add an internal method in there to call it call it. Your retriever/saver will then call the internal method. Does that make sense? I can post more code if necessary..
Best of luck,
Justin

Related

Something akin to "Sparse Fieldsets" in .NET

I'm trying to find the vocabulary to describe what I want and if it exists.
I have a table that shows a few data points from large objects. Loading the entire objects just for the table is very slow. Is there a way to only pass to the front the few properties I want without having to define a new object?
I found something called Sparse Fieldsets in JSON API, and I'm wondering if something like this exists for .NET under another name.
Update:
Talking to another coder, I realize it probably makes more sense to implement something like this between the backend and the database and make a specific call for this table. I still need to work out if I need to create a new object to support this. I think it'd still be faster if I just kept the same object but nulled out all of the connecting objects that I don't need for the table. But maybe that's considered bad practice? Also we're using Entity Framework for what it's worth.
Update 2:
I just created a new query without all of the .Include() and works well enough for what I need:
_dataContext.ApplePie
.Include(f => f.Apples).ThenInclude(f => f.Apple)
.Include(f => f.Sugars).ThenInclude(f => f.MolecularStructure)
.Include(f => f.Recipe)
Maybe you are looking for Anonymous Types?
For example, if you had a typed object with three properties, but you only wanted to operate on two:
var threePropThing = new ThreePropertyThing { Id = 1, Message = "test", ExtraProperty = "ex" };
var myAnonThing = new { Id = threePropThing.Id, Message = threePropThing.Message };
Best practice would be to not pass this anonymous object around. But, if you really needed to, you could return it as type object.
Typically, when passing data around in c#, you want to have it typed.
C# is a strongly-typed language and I would say that it is unusual for C# to support scenarios, when object definition (properties) are not known in advance, like in JSON API "fields" parameter case. Implementing this would imply using reflection to filter the properties, which is usually slow and error-prone.
When implementing C# web-services, people usually create one DTO response model per each request.
If your table has fixed set of fields, I would personally recommend to create a DTO class containing only the fields which are required for your table, and then create a method which returns this response for your specific request. While it doesn't align with "without having to define a new object" in the question, it makes the intention clear and makes it really easier to maintain the API in future.
You might want to use libraries like AutoMapper to save time and avoid duplicated code of copying the values from data model to DTO, if you have many such methods.

Communication between Flex module and Application

Ok, modules in Flex are popular but I have no idea why documentation and examples on the different uses of Flex modules can be so scarce.
Anyway, for this question, I will take the classic Employee/Department example. I have a main.mxml that contains an mx:TabNavigator. Each tab is loaded by an s:ModuleLoader.
Tables: Employees {empID,empName,deptID}, Deparments {deptID,deptName}
The Tab Navigator contains only one tab (for our example) called Employee. I have an Employee.mxml module. In that module, I have a datagrid that is populated with Employee details. I use the getEmployees($deptID) function. This function, as you may guess, returns me an array of Employees who work in a particular department.
Outside the TabNavigator, I have a departmentDropDownList that is populated with departments.deptName.
My objective is to load the Employee module when I select a particular department from the DropDownList. I have a changeHandler for the DropDownList that can give me the deptID.
protected function departmentDropDownList_changeHandler(event:IndexChangeEvent):void
{
MyDeptID=departmentDropDownList.selectedItem.deptID;
//var ichild:*=employeeModule.child as IModuleInfo;
}
Now, the million dollar question is: How do I pass this deptID to the Employees module. The latter has an employee_creationCompleteHandler that calls getEmployees(deptID):
protected function EmployeesDg_creationCompleteHandler(event:FlexEvent):void
// I only need to get the deptID from the departmentDropDownList outside the Employee module.
// If I could create a global variable deptID, that would be great!
getEmployeessResult.token=employeeService.getEmployeess(deptID);
}
I have attempted to use [Bindable] variables but without success.
I would appreciate your suggestions.
You can't really guarantee that the deptID will be set when creationComplete runs--it sounds like you're waiting for a server result--so this is probably not the best way to handle it.
One of the things you need to be careful of is directly referencing the full Module Class from the main Application, because the point of modules is that you should not compile in the module Class into the main Class (to reduce file size/load times).
So what you might want to do is create an Interface. This creates a "contract" between the main application and the Module without carrying all the implementation code with it. That might look something like this
public interface IEmployeeModule {
function set deptID(value:int):void;
}
Then, your Module might have code that's something like this:
protected var _deptID:int;
public function set deptID(value:int):void {
_deptID = value;
var token:AsyncToken=employeeService.getEmployeess(deptID);
token.deptID = value;//in case department id changes, you can determine if you still care
}
Note that, though global variables seem like a wondermous idea when your project is small, they are a very bad habit to get into. It can be almost impossible to repair a project that starts out with these and then grows to the point that no one can figure out exactly which of the hundreds or thousands of Classes that have access to a variable are changing it in the wrong way at the wrong time.
You ESPECIALLY don't want to use global variables with Modules, as they can cause really bad problems when the modules start fighting over the definition.
We solved this problem with the use of Cairngorm v2. Think of it as a message bus for ActionScript, one of several. In your departmentDropDownList_changeHandler method we would create a DeptChanged event with the ID as the payload, and send it on the bus to any and all subscribers to that message type. It worked pretty well for us, and made things more event driven, which in some circles is considered a good thing in itself.
#J_A_X I haven't had good luck with using Robotlegs out of the box with Modules. It seems that something goes wonky with the security contexts, even though it shouldn't. I had to use Joel Hooks' ModuleContext to make it work right, even though my needs were fairly basic.

NHibernate.IFutureValue<> when serialized includes .Value

I'm building an ASP.NET (2.0, no, I can't change it) site with NHibernate, and have a custom JSON converter so I can not-serialize properties I want hidden from the client. This lets me just return the objects, and never have to worry about their serialized values - they're always secure.
Unfortunately, it appears that if I use query.FutureValue<class>(), the object that gets serialized is first the NHibernate.Impl.FutureValue<class> and not my entity, which means I get JSON that looks like this if I throw it in a dictionary and return it to the client:
{key: { Value: { /* my serialized object properties */ } }
Previously I discovered that I can't get any interfaces to work in ASP's JavaScriptConverter implementations... only regular or abstract classes. So returning typeof(IFutureValue<MyBaseClass>) as a supported type means my converter is completely ignored. I can catch MyBaseClass, because I refactored things earlier to use an abstract base instead of an interface, but not the interface.
And then I discover that the FutureValue implementation in .Impl is internal to the assembly, or some other such nonsense that only serves to make my .NET experience even more painful. So I can't use typeof(FutureValue<MyBaseClass>) to handle it all, because FutureValue exists only in my debugging sessions.
Is there a way to get the class type out of the assembly? Or a way to convince ASP that interfaces do in fact have uses? Or might there be some superclass I can access that would let me get around the whole issue?
Help! I like my Futures, it lets me batch a whole heck-ton of calls at once!
(if something isn't clear, or you want more code, by all means, ask! I can post quite a bit.)
If I'm understanding you correctly, it seems you are mixing things a together a little bit.
It sounds like you're trying to serialize an instance of query.FutureValue<class>(), which unsurprisingly gives you just that: a JSON object where the Value fields has JSON representing your entity.
To me it sounds like you really want to just serialize query.FutureValue<class>().Value.
Using NHibernate futures like this gives you little benefit though, so you're probably after something like:
var future1 = query1.FutureValue<SomeEntity>();
var future2 = query2.FutureValue<AnotherEntity>();
var json1 = serializer.Serialize(future1.Value); //<BAM! Multi-query gets fired!
var json2 = serializer.Serialize(future2.Value);
Does that make sense?

asp.net subsonic 2.2 paging linked table collection

I'm creating a small forum for my CMS and I'm using subsonic 2.2 as my DAL.
I'm loading my theads like this:
DAL.ForumThread item = DAL.ForumThread.FetchByID(id);
In my database my ForumPosts table looks like this:
ForumPostID | ThreadID | Description | UserID | CreatedOn| etc
So now when I have my DAL.ForumThread item I can load the connected post collection by using:
item.ForumPosts();
This all works great, but the problem is that I'm using serverside paging and want to add some additional select parameters too like showing only active records.
Is this even possible when using SubSonic 2.2 ? The workaround I have now is just creating a new SubSonic.Query and select the posts by threadid and there I can set pageindex and pagesize without problems but I think this can be done easier?
I also would like to know if it makes any difference performance wise by just using item.ForumPosts() or starting a new query, I think the forumposts are already in the ForumThreads collection and don't require a new database call right?
I hope someone can point me in the right direction!
Thank you for your time and merry christmas.
Kind regards,
Mark
This goes a bit late, but. You can instead of using the Query tool use something like this:
ForumPostsCollection posts = new ForumPostsCollection().Where(ForumPosts.Columns.ThreadId,1).Load();
You can use as many parameters as you want just repeat the where clause like:
ForumPostsCollection posts = new ForumPostsCollection().Where(ForumPosts.Columns.ThreadId,1).Where(ForumPosts.Active,true).Load();
You can even use a comparison in the one of the Where methos overloads.
A for paged results, I am sure you can do it, but I dont have subsonic here with me atm, and i cannt find anything in the docos for version 2.2, there is something for v3 though.
About your second question, Subsonic uses Lazy Loading of collections, meaning that when you execute the method ForumPosts, it issues another database call to fecth that collection. The same is not true for Parent entities, the rule here is if its a method eg: ForumPosts() - A new database call is done, it it is a property eg: post.Thread it will be loaded.

ASP.NET MVC - getting started with Linq and SQL procedure

Today is my first day using ASP.NET MVC, and I'm finding it very intriguing. I only just started learning asp.net.
So basically I'm trying to call a procedure from an MSSQL database, and with it I need to send a paramater "PlaceID", which is an integer. This procedure basically just picks out a number of columns from different tables in the database. Here is the Linq to SQL code
The ultimate goal is to be able to retrieve all the information and return it as JSON with a function that will be available for a javascript.
I'm wondering what is the best way to proceed from here. I know I have to create a view, but I'm still unclear exactly on how I can call the procedure and make it store all the information. I could really use some help on this, some code examples would be excellent. I already wrote a C#.net function to convert a datatable to JSON using a stringbuilder, but I get the feeling there is a smarter way to do things.
Any help is very appreciated.
Might I suggest going through the NerdDinner.com example first. I really think that you may have started down the wrong road and it would be worth backing up and doing some review first. For one thing, you probably don't want to be mixing DataTables and LINQ, typically you'd work with strongly-typed models and have your data context/repository return IQueryable/IEnumerables of the model instead of a DataTable. For another, there is a controller method that is able to turn a model into JSON for you. Generally, you should need to write your own JSON serialization.
Declare a list and serialze it into json.
Here Lstcustomeris a genric list of class type customer
I Assign values to class varable and then insert this class in list of Lstcustomer
e.g.
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Return js.Serialize(Lstcustomer)

Resources