473,790 Members | 3,246 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Caching DLinq ExecuteQuery results

I implemented cached DLinq ExecuteQuery method.
However some queries are run against database always because keys
are not found in cache.

Maybe equality comparer or other parts of implementation are wrong and/or
inefficient.

How to fix this code ?
Which is best way to create static ExecuteQuery method which caches all
queries during
application lifetime ?

Andrus.
using System;
using System.Collecti ons.Generic;
using System.Data;
using System.Linq;
using System.Text;

class DLinqCache
{

class Key
{
/// <summary>
/// Sql command text possibly containing {n} parameters
/// </summary>
internal string CommandText;

/// <summary>
/// Command parameter values: scalar types present in sql server
types like int, int?, decimal, decimal?, string, DateTime, DateTime?,
/// float, bool, bool?, double.
/// </summary>
internal object[] Parameters;

/// <summary>
/// Entity types from which this query depends
/// </summary>
internal Type[] SourceTables;
}

static Dictionary<Key, objectcache;

/// <summary>
/// Main entry point for all cached non-linq queries.
/// Remember query in cache.
/// </summary>
/// <param name="source">t ypes whose or whose child types query is
depending.
/// Spectial values:
/// null - volatile. query is not cached
/// empty array - permanent. cache is cleared only on company cahnge or
re-login or windws clear command.
/// </param>
public static IEnumerable<TEn tityExecuteQuer y<TEntity>(stri ng command,
Type[] src, params object[] prm)
where TEntity : new()
{
// todo: implement weak reference cache?
var key = new Key { SourceTables = src, CommandText = command,
Parameters = prm };
if (cache != null)
{
if (src != null)
{
object res;
if (cache.TryGetVa lue(key, out res))
return (IEnumerable<TE ntity>)res;
}
}
else
{
cache = new Dictionary<Key, object>(new KeyComparer());
}

using (var db = new Database())
{
IEnumerable<TEn titytul = db.ExecuteQuery <TEntity>(comma nd,
prm);
cache.Add(key, tul);
return tul;
}
}
static DataChanged( Type entity ) {
foreach (var k in cache.Where(k =>
IsSubclassOf(k. Key.SourceTable s, entity)))
cache.Remove(k. Key);
}
class KeyComparer : IEqualityCompar er<Key>
{
public bool Equals(Key x, Key y)
{
if (x.CommandText != y.CommandText)
return false;
if (x.SourceTables .Length != y.SourceTables. Length ||
x.Parameters.Le ngth != y.Parameters.Le ngth)
return false;

for (int i = 0; i < x.SourceTables. Length; i++)
if (x.SourceTables[i] != y.SourceTables[i])
return false;

for (int i = 0; i < x.Parameters.Le ngth; i++)
if (x.Parameters[i].ToString() !=
y.Parameters[i].ToString())
return false;
return true;
}

public int GetHashCode(Key obj)
{
return obj.GetHashCode ();
}
}

static bool IsSubclassOf(Ty pe child, Type parent)
{
return child == parent || child.IsSubclas sOf(parent);
}

static bool IsSubclassOf(Ty pe[] childs, Type parent)
{
return childs.Any(c =IsSubclassOf(c , parent));
}
}

Nov 2 '08 #1
0 2456

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1868
by: Senna | last post by:
Hi Have a question about DLinq. The example code floating around looks like this: Northwind db = new Northwind(@"C:\...\northwnd.mdf"); var custs = from c in db.Customers where c.City == "London" select c; How does this work. Will it retreive all the rows from the Customer table
3
1719
by: Chiranjib | last post by:
I have the following queries/Observations about DLINQ. 1. I could not find any direct way of handling many to many relations. Suppose if User and Role are related by a join table UserRole then I should be able to have a collection of Roles in User and vice versa. Which i think is not possible in DLINQ. (Please correct me if I am wrong) 2. State management is handle outside entities. In scenareos where a client grabs a entity from a...
0
1233
by: Scott Nonnenberg [MSFT] | last post by:
This is our first official DLinq chat. We're still early in the planning and development stage for this very cool technology, so we can react to your feedback much more easily. Show up and tell us what's on your mind! Scott Nonnenberg Program Manager Visual C# Team DLinq "The LINQ Project is a codename for a set of extensions to the .NET
0
1106
by: Scott Nonnenberg [MSFT] | last post by:
The DLinq team will be ready and waiting for your questions and comments at this date and time at this location: http://msdn.microsoft.com/chats/chatroom.aspx. This is otherwise known as a chat - a great opportunity to speak directly with the people who develop the software you might just end up using! See you there! Scott Nonnenberg Program Manager Visual C# Team
0
1168
by: Scott Nonnenberg [MSFT] | last post by:
Show up and talk to members of the DLinq team. What's DLinq, you ask? Well, to understand that you'll need to know what LINQ is - you can start with the blurb below, read more about it here: http://msdn.microsoft.com/data/linq/, and install the latest CTP: http://www.microsoft.com/downloads/details.aspx?familyid=1e902c21-340c-4d13-9f04-70eb5e3dceea&displaylang=en It's very cool stuff. Scott Nonnenberg Program Manager
4
1460
by: Brett Romero | last post by:
I've downloaded the DLINQ samples from Microsoft and have always been able to compile these in VS.NET 2005 Pro. I have a new project that I added DLINQ references to and put in a simlpe query. It didn't compile. I went back to the SampleQueries.sln, compiled and for the first time it failed. It keeps looking at the query code as if it were regular c#. It's wanting ";", which the queries don't use. Same thing is occuring in my other...
4
2985
by: Hermann | last post by:
My site is a bit slow showing the main page so I thought caching query result in PHP will improve performace. Then I read MySQL documentation and saw that MySQL does have a caching feature. So... now I dont know if doing the PHP caching is worth the pain. Would there be any noticed performace improvement if I cache query results in PHP, considering that MySQL is already caching the queries? Thanks
9
1688
by: Marc Gravell | last post by:
How to fix ? Write it the way that you know works... (i.e. the one you commented out), or write that parses the input string doing a Split on '.', and uses reflection to navigate the child hierarchy. Which isn't something I have time to do right now... Marc
1
2190
by: Michel Walsh | last post by:
In the same spirit, but more LINQ related, you can also use ExecuteQuery: var query = dataContext.ExecuteQuery<className>( @"SELECT ... WHERE ... AND... OR... "); where className is appropriate to recuperate the result of your dynamically built SQL statement, as a string.
0
9666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9512
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10201
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9987
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9023
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5424
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4100
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2910
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.