I am using Entity Framework with Asp.net
i need to return database name dynamically from my model
i using the following code but it return empty string
ResturantEntities db = new ResturantEntities();
string databaseName = db.Connection.Database;
any help thanks
Related
I am learning asp.net core mvc and API. I can simply work on it for CRUD operation. But, I get confused for accessing data from multiple tables like listing all categories with showing number of items each categories contains. What I need to learn for example Lina, entity framework code first, ado.net? I am currently using entity framework code first.
Thanks
Learn Dapper a simple object mapper for .NET.
What I Understood from your problem is that you have multiple tables and you want to query them and map the query result in your c# or vb code.Here I will show simple mapping of query result to c# objects.
Suppose you have three tables category_1,category_2 and category_3.
Lets say each table have two columns named itemName and ItemValue.
Lets create c# class corresponding to each table.
class category_1{
string ItemName {get;set};
int ItemValue {get;set;};
}
class category_2{
string ItemName {get;set};
int ItemValue {get;set;};
}
class category_3{
string ItemName {get;set};
int ItemValue {get;set;};
}
Suppose your querying three tables and map the result of query to respective object in c#.
let our sql query be as follows:
string sql = #"select * from category_1;select * from category_2;select * from category_3;"
Here we have three select statements and each select statement will give you result of respective table.Lets query the above sql to database using dapper and map them to c# object as follows.
List<category_1> lstCotegory1 = new List<category_1>();
List<category_2> lstCotegory2 = new List<category_2>();
List<category_3> lstCotegory3 = new List<category_3>();
using (var multi = connection.QueryMultiple(sql))
{
lstCotegory1 = multi.Read<category_1>().ToList(); // map first select statement
lstCotegory2 = multi.Read<category_2>().ToList(); // map second select statement
lstCotegory3 = multi.Read<category_3>().ToList(); // map third select statement.
}
This is how you can return results of multiple queries and map them to appropriate object. I know you can do better than this but to understand we have to go with simple example.Hope this will help.
I am working on an asp.net mvc web application, that connects to two different DB (I name them dbA & dbB). Currently I need to create a JSON object that contains values from different tables.
The two table are as follow:-
Table Technology from dbA, have the following fields:-
>> dbAID , Tag , db2ID
While table Resource from dbB have:-
>> Db2ID , Name
I have the following Action method:-
public ActionResult AutoComplete(string term)
{
var tech = dbA.Technology.Where(a=>a.Tag.StartWith(term));//select all technology that have their tags start with passed term
var db2IDList = tech.Select(a=>a.db2ID).ToArray();//create a list of db2ID
var resource = dbB.Resource.Where(db2IdList.Contains(a=>a.dbBID));//get the resource based on the db2IDList
JsonResult j = newJsonResult();
//here I want the json to contain the Technology.Tag + ResoruceNane, where the join is based on the db2Id stored insdie the technology table
}
So can anyone adivce what is the best way to construct my JSON object?
Thanks
Anonymous Types: http://msdn.microsoft.com/en-us/library/bb397696.aspx
And the framework provided JsonResult, generated by the Json(object) helper.
e.g. return Json(new { field1 = resource.fieldOne, field2 = resource.fieldTwo })
you can construct a List i think its easier :
List<Object> _return=new List<object>();
_return.Add(Technology.Tag);
_return.Add(ResoruceName);
Return Json(new {Success=true, _return});
//and then cast get these object in your Javascript , it would be an easy to use array
I have created a simple stored procedure in SQL Server 2008 as:
CREATE PROCEDURE viewPosts
AS
SELECT * FROM dbo.Post
Now, I have no idea how to use it in controller's action, I have a database object which is:
entities db = new entities();
Kindly tell me how to use stored procedure with this database object in Entity Framework.
For Details check this link:
http://www.entityframeworktutorial.net/data-read-using-stored-procedure.aspx
Hope this will help you.
See article about 30% in:
In the designer, right click on the entity and select Stored Procedure mapping.
Click and then click the drop down arrow that appears. This exposes the list of all Functions found in the DB metadata.
Select Procedure from the list. The designer will do its best job of matching the stored procedure’s parameters with the entity properties using the names. In this case, since all of the property names match the parameter names, it maps every one correctly so you don’t need to make any changes. Note: The designer is not able to automatically detect the name of the field being returned.
Under the Result Column Bindings section, click and enter variable name. The designer should automatically select the entity key property for this final mapping.
The following code is what I use to initialize the stored procedure, then obtain the result into variable returnedResult, which in this case is the record id of a newly created record.
SqlParameter paramResult = new SqlParameter("#Result", -1);
paramResult.Direction = System.Data.ParameterDirection.Output;
var addParameters = new List<SqlParameter>
{
new SqlParameter("#JobID", EvalModel.JobID),
new SqlParameter("#SafetyEvaluator", EvalModel.SafetyEvaluator),
new SqlParameter("#EvaluationGuid", EvalModel.EvaluationGuid),
new SqlParameter("#EvalType", EvalModel.EvalType),
new SqlParameter("#Completion", EvalModel.Completion),
new SqlParameter("#ManPower", EvalModel.ManPower),
new SqlParameter("#EDate", EvalModel.EDate),
new SqlParameter("#CreateDate", EvalModel.CreateDate),
new SqlParameter("#Deficiency", EvalModel.Deficiency.HasValue ? EvalModel.Deficiency.Value : 0),
new SqlParameter("#DeficiencyComment", EvalModel.DeficiencyComment != null ? EvalModel.DeficiencyComment : ""),
new SqlParameter("#Traffic", EvalModel.Traffic.HasValue ? EvalModel.Traffic.Value : 0),
paramResult
};
// Stored procedure name is AddEval
context.Database.ExecuteSqlCommand("AddEval #JobID, #SafetyEvaluator, #EvaluationGuid, #EvalType, #Completion, #ManPower, #EDate, #CreateDate, #Deficiency, #DeficiencyComment, #Traffic, #Result OUTPUT", addParameters.ToArray());
var returnedResult = paramResult.Value;
NewEvaluationID = Convert.ToInt32(returnedResult);
I have a form built in webmatrix that will be updating data within a user specified database.
I would like the user to insert their DB name into the form, and have the Database.Open("SQLServerConnectionString"); open based on the users submission.
if not possible, is there a way to simply include the user specified DB name within the SQL query below within webmatrix? Sample of what I have below:
var db = Database.Open("SQLServerConnectionString");
var selectQueryString = "SELECT donor_id,first_name,last_name FROM SUPPORT.dpo.dp WHERE donor_id=#0";
I would like the static "SUPPORT" database in the FROM clause to be updated dynamically based on user input. Any help would be great.
Are you using .mdf files or actual database connection strings? If connection strings you can use the OpenConnectionString method and pass a custom connection string instead of using whats in the web.config.
http://msdn.microsoft.com/en-us/library/gg569301(v=VS.99).aspx
Something like this would probably work:
#{
var databaseName = Request["databaseName"]; //load from request
var connectionString = string.Format("Data Source=.\\SQLExpress;Initial Catalog={0};Integrated Security=True", databaseName);
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}
You can just drop the SUPPORT. prefix as its not necessary for the select statement.
hi
I've developed an application using strong-typed dataset with .net framework 3.5.
is there a way to change the source table for a tableadapter programmatically?
thnx
There are a couple of ways that you can do this. First you could just add a new query that pulls from the different table, and then execute the method for that query, as long as the columns match it will work.
If you need to dynamically change the one of the statements you can access the command collection of the table adapter, it is protected though, so the easiest way to do this is to create a partial class to extend the one generated by the designer. Once you do this you can add your own method to return the data. You can use adapter.CommandCollection[0].CommandText to get and set the SQL for the the default GetData command that is created.
Once you do this you can change it, clear out the parameters, add new parameters or whatever you want to do, then you set the CommandText with the altered SQL, and call GetData or whatever you named the command and it will execute and return as usual.
Here is a code example:
using System.Data.SqlClient;
namespace DataTableAdapters
{
public partial class Data_ItemTableAdapter
{
public Data.Data_ItemDataTable GetDynamicExample(string SearchValue)
{
using (Data_ItemTableAdapter a = new Data_ItemTableAdapter())
{
SqlCommand cmd = a.CommandCollection[0];
cmd.Parameters.Clear();
string SQL = #"Select Data_Item_ID, Data from Data_Item where
SearchValue = #SearchValue";
cmd.CommandText = SQL;
cmd.Parameters.AddWithValue("#SearchValue", SearchValue);
return a.GetData();
}
}
}
}