All of my existing using statements look like the following:
using (var context = new AppContext())
{
}
Now what if I want to use Dapper to pass a sql string directly to the database rather than:
context.Database.SqlQuery(sql);
After looking at the Dapper documenation it looks like it just uses a regular connection string. I am unsure of how to adjust my using statement declaration.
I want to be able to do the following like all of the Dapper examples show:
connection.Query(sql);
I am really hoping dapper will help me with populating custom properties. For example I used a partial class to extend one of my entity framework properties. Currently when I use pass a sql query through linq this property does not get populated even though it is in the Select.
Just use context.Database.Connection.Query<T>() from Dapper since it is just an extension to DbConnection.
Related
I have a connection string and I want to use LINQ to query a remote database. In the Microsoft example they use the DataContext class. However the DataContext does not appear in Intellisense. It says that it uses 'System.Data.Linq` but I am not seeing that either. http://msdn.microsoft.com/en-us/library/bb350721(v=vs.110).aspx
Is there a Hello World example for using a connection string and LINQ?
public void SimpleQuery()
{
var connectionString = #"Server=10.1.10.1;database=Mydatabase;uid=myusername;password=mypassword;";
DataContext dc = new DataContext(connectionString);
var q =
from n in dc.table
select n;
Console.WriteLine(n);
}
Well, that is not how it works or at least it is not that simple.
In order to be able to run linq queries against your DB, first you need to map your db tables to dot net classes.
You can do that in various ways, for example you can use Linq to Sql, or Entity framework.
For EF, you need to decide which EF approach you are going to use (Model First,Code First etc.) Then you should configure your settings and create your db context.Take a look at Entity Framework documentation for more details...
Is there a way to use Linq-to-SQL with nhibernate envers to query through revisions without having to use envers audit expressions?
I would like to avoid using something like this, which requires hardcoded string property names:
reader.CreateQuery()
.ForEntitiesAtRevision(1)
.Add(AuditEntity.Property("FirstName").Eq("bob"))
.Results();
No. The only built in query api is the "criteria like" you mention.
In order to acces my db and use my stored procedures I made this very simple data access layer (if someone can call this "layer"). I have 8 files where each file looks like:
using System;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
public class TasksDBHandler
{
private static Database db = DatabaseFactory.CreateDatabase("DBNAME");
public static void SetTaskDepreciationData(long taskId, long fieldId, string value)
{
DbCommand command = db.GetStoredProcCommand("dbo.P_CUS_TSK_SetTaskDepreciationData");
db.AddInParameter(command, "#task_id", DbType.Int64, taskId);
db.AddInParameter(command, "#field_id", DbType.Int64, field);
db.AddInParameter(command, "#value", DbType.String, value);
db.ExecuteNonQuery(command);
}
//Many more stored procedures calls
}
I want to build a new and better data access layer but I don't know how should it look like. I want the ability to use stored procedures without the need to write static method for each stored procedure, I want better connection menagement and so on/
Is anyone have any clue how to do so?
I am using .Net and SQL SERVER.
Have you looked at any of the ORM products out there? There's Linq2Sql, Entity Framework, NHibernate, and others. Unless what you need to do is very basic, you'll probably have better results learning to use an existing framework than trying to write your own.
In an ORM like Entity Framework, you typically don't manage your connection manually, it defines an object (or entity) model from your database and a "context" which is responsible for retrieving the data from your database and mapping it to the correct properties on the classes in your entity model. So you request something from the context, it loads the data necessary to fulfill your request into memory, you work with it like other classes, and then tell the context to save your changes back to the database. There are several ways to interact with your entity model in entity framework, but the example I'll use is Linq2Entities. You write a Linq query, and the context is responsible for turning that into a query against the database *disclaimer: I haven't tried to run this code, it's just meant to serve as an example
using(MyEntitiesContext context = new MyEntitiesContext())
{
var idleUsers = from u in context.User
where u.LoggedIn && u.LastActivity > DateTime.Now.AddMinutes(-30)
select u;
foreach(User u in idleUsers)
{
u.Status = UserStatus.Idle;
}
context.SaveChanges();
}
Obviously there's a lot going on behind the scenes:
There's the whole object model that gets generated from your database (you select the tables you want to be included in your model, and you can create multiple models in the same project).
There's the context, which manages the database connection and turns your Linq expression into a database query
There's the connection string that has to be defined your .config file so Entity Framework knows how to connect to your database
You should be able to find plenty of information on Entity Framework, but the easiest way I've found to learn is to jump in and start trying to do something, and then find answers to questions as they come up. I wouldn't try to use it right away on something highly critical or time sensitive, as there's definitely a learning curve, and you'll learn better ways of working with it once you've experienced some of the pitfalls.
Here's a link to Microsoft's Entity Framework 4 Quickstart which should give you something fairly straightforward to try out. Have fun!
I am new to Linq to Entities and I am trying to insert a record using the linq syntax.
I have created the edmx file and instatiated it in a class with:
PasswordEntities db = new PasswordEntities();
I have a method that looks like this:
public void InsertRecord(Password record)
{
db.AddToPasswords(record);
}
But intellisense tells me that AddToPasswords is a deprecated method and to consider using the .Add method of the associated ObjectSet property instead.
I am running VS 2010 under Framework 4.0.
What would be the syntax to do this?
How about:
db.Passwords.AddObject(record);
Aside: It seems foolish to me to use the word Object in naming classes and methods in an OO world as the EF designers have done. Of course I'm adding an object, that's all we have around here. Does ObjectContext really tell me more about what the context is about than Context?
This is weird. AddToPasswords() would be a generated method. How can a custom generated method be obsolete?
Anyway the syntax for the generic add method ( assuming db is an ObjectContext ) is:
public void InsertRecord(Password record)
{
db.AddObject("EntitySetName", record);
}
I create a EDM using my database and saw that while it was able to make relations like
Customers.First().Orders
there is nothing like
Customer.First().Orders.FindOrderByOrderID()
Customer.First().Orders.FindOrderByOrderName()
etc.
Maybe I was expecting it to be like that and that's how it doesnt work
and I will probably just have to LINQ to entities and create mangers that handle business logic in them.
or does LINQ to SQL do this?
You can use LINQ with the Orders property, like this:
var order = Customer.First().Orders.FirstOrDefault(o => o.OrderId == someId);
This will return null if there was no matching Order.
With LINQ to Entities you can do this. Such as the example SLaks posted above.
If you're feeling adventurous, it is possible to write a function to do this. Since Entity Framework knows which column is the primary key it is possible to write a function like GetEntityByPrimaryKey.
CodeProject has an article regarding the repository pattern and if you search for "SelectByKey" you'll see their implementation of that. I use something similar and find it very helpful.
The idea is that you can use LINQ to write more flexible queries. Note, however, that you could probably so something like FindOrderByOrderName in .NET 4.0 by creating your own dynamic type (not trivial), that responded to calls following this pattern by building a LINQ query automatically. You'd lose intellisense, of course, and I doubt it would be worth it, but it could be done.