Linq To Sql Conversation In Wcf Service - sql-server

Can you please provide an answer following sql query to linq . I have some knowledge about linq but i am confused about sql reader object ..
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
var cmd = new SqlCommand("SELECT Account_Type,Account_Fees,Account_Balance,Over_Draft_Limit FROM Current_Account_Details WHERE Account_Number = '" + accountNumber.Account_Number + "'", conn);
cmd.CommandType = CommandType.Text;
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while (reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
accountNumber.Account_Type = reader["Account_Type"].ToString();
accountNumber.Account_Fee = reader["Account_Fees"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}

First you have to have DbContext which you must instantiate in using(usual practice):
using (DbContext db = new DbContext())
{
var results = (from ad in db.Current_Account_Details
where ad.Account_Number == accountNumber.Account_Number
select ad).ToList();
}
Make sure you have created the object data model from database.
I do not get the other part of your post but this would be the general idea of how to write Linq2Entities queries.

Related

How to copy all schema from one database to other database (created at runtime)?

I have used schema for tables for one database,so how to copy all schema from one database to other database(database created at runtime)
string sql = "create database " + str1;
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
command.ExecuteNonQuery();
Response.Write("database created");
connection.Close();
string sqll = "(select * into " + str1 + ".cost_category.cost_category_info
from ERPAccounting.cost_category.cost_category_info where 1=2)
(select * into " + str1 + ".dbo.cost_centre_info from
ERPAccounting.cost_centre.cost_centre_info where 1=2)"
connection.Open();
SqlDataAdapter ad = new SqlDataAdapter(sqll, connection);
DataSet ds = new DataSet();
ad.Fill(ds);
Using C#, object DDL can be obtained by using SMO objects and then executed in the database where the objects need to be copied to. In the example below, references to Microsoft.SqlServer.Management.Smo, Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc, and System.Data.SqlClient are necessary. The DDL is first obtained from the SMO objects, then it used as the CommandText for the SqlCommand that is executed in the destination database. This example is for tables, but other objects (views, stored procedures, etc.) can also be copied using this method.
//set initial catalog to destination database
string connStr = #"Data Source=YourServer;Initial Catalog=DestinationDatabase;Integrated Security=SSPI;";
using (SqlConnection conn = new SqlConnection(connStr))
{
//set source server and database using SMO objects
Server srv = new Server(#"YourServer");
srv.ConnectionContext.LoginSecure = true;
srv.ConnectionContext.StatementTimeout = 600;
Database db = srv.Databases["SourceDatabase"];
//configure Scripter for DDL
Scripter script = new Scripter(srv);
ScriptingOptions scriptOpt = new ScriptingOptions();
//SQL command to execute DDL in destination database
SqlCommand sql = new SqlCommand();
sql.Connection = conn;
conn.Open();
//this can changed to views, SPs, etc. as needed
foreach (Table t in db.Tables)
{
//check for system objects
if (!t.IsSystemObject)
{
StringCollection sc = t.Script(scriptOpt);
foreach (string s in sc)
{
//assign and execute DDL
sql.CommandText = s;
sql.ExecuteNonQuery();
}
}
}
}

How to import data from Excel sheet to database in c# with LINQ?

I have three columns in Excel sheet such as id, name, family.
I am using LINQ and i need to import data from Excel to database with coding instruction, i have 6500 records in Excel sheet
You can use below code to get all the data and then you can convert form DataTable to List. for below example to work you have Microsoft Access Database Engine 2010 Redistributable
should be installed
public static DataTable ReadExcelWithoutOffice(string filePath)
{
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES;TypeGuessRows=0;FirstRowHasNames=true;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
var ds = new DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
}
}
Thank you all for your answer.
I found my problem. Here is the code :
string pach = #"D:\C# Projects\ex.xlsx";
var excelData = new ExcelQueryFactory(pach);
var data = from x in excelData.Worksheet<xlsdata>("MySheet")
select x;
DataClassesDataContext db = new DataClassesDataContext();
foreach (var d in data)
{
db.tbl_infos.InsertOnSubmit(new tbl_info
{
id = d.id,
name = d.name,
family = d.family
});
}
db.SubmitChanges();
You will need to import and reference OpenXML, open the sheets, sheet, worksheet, IIRC - then parse through your columns into strings.
OpenXML
Then create a SQL Data Adapter and all of that, to use either a ConnectionString or SQLConnection, fire up a parameterized query, and it's in the database.
SQL Example

Is Referential integrity between tables mandatory for custom conflict resolver in sql merge replication?

I have a database which have multiple tables but these tables have not any relationship define(Referential integrity) in database.
They are related to each other but maintained by trigger and application.
I have created custom conflict resolver on Microsoft SQL server 2008 R2 merge replication. In custom conflict resolver, I am checking subscribers priority by SQL query from publisher database and based on that priority. I am resolving the conflict in replication data-table.
Custom Conflict Resolver Code as below
public override ActionOnUpdateConflict UpdateConflictsHandler(DataSet publisherDataSet, DataSet subscriberDataSet, ref DataSet customDataSet,
ref ConflictLogType conflictLogType, ref string customConflictMessage, ref int historyLogLevel, ref string historyLogMessage)
{
// Priority column AcceptDate
DateTime? publisherModifiedDate = string.IsNullOrWhiteSpace(Convert.ToString(publisherDataSet.Tables[0].Rows[0]["AcceptDate"])) ? new Nullable<DateTime>() : DateTime.Parse(publisherDataSet.Tables[0].Rows[0]["AcceptDate"].ToString());
DateTime? subscriberModifiedDate = string.IsNullOrWhiteSpace(Convert.ToString(subscriberDataSet.Tables[0].Rows[0]["AcceptDate"])) ? new Nullable<DateTime>() : DateTime.Parse(subscriberDataSet.Tables[0].Rows[0]["AcceptDate"].ToString());
//Get priority via userid
int publisherUserId = Convert.ToInt32(publisherDataSet.Tables[0].Rows[0]["UserId"]);
int subcriberUserId = Convert.ToInt32(subscriberDataSet.Tables[0].Rows[0]["UserId"]);
DataTable dt = new DataTable();
//Publisher
using (SqlConnection sqlConnection = new SqlConnection(AppConfig.PubliosherConnectionString))
{
SqlCommand cmd = new SqlCommand("select * from RISubscriber where UserId=" + publisherUserId, sqlConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
int publisherPriority = Convert.ToInt32(dt.Rows[0]["SubscriberPriority"]);
//Subcriber
dt = new DataTable();
using (SqlConnection sqlConnection = new SqlConnection(AppConfig.PubliosherConnectionString))
{
SqlCommand cmd = new SqlCommand("select * from RISubscriber where UserId=" + subcriberUserId, sqlConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
int subcriberPriority = Convert.ToInt32(dt.Rows[0]["SubscriberPriority"]);
if (subcriberPriority > publisherPriority)
{
customDataSet = subscriberDataSet.Copy();
}
else
{
customDataSet = publisherDataSet.Copy();
}
return ActionOnUpdateConflict.AcceptCustomConflictData;
}
Question: I want to replicate the data between subscribers based on custom conflict resolver and want to maintain the data integrity between tables.
Please let me know. If you have any idea.
How we can do it?
Thank you

How can we use both sql and oracle database connection using one object only

I wants to fetch the data from database using C++.Net. I need to do this irrespective of db used in the system. But i don't want to change my code for each database. I am looking for a solution in C++.Net, please do help..
This is what i have now;
Oracle:
OracleConnection *myOracleConnection;
OracleDataAdapter * myDataAdapter;
DataSet * myDataSet;
myOracleConnection = new OracleConnection(S"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw;");
myOracleConnection->Open();
myDataAdapter = new OracleDataAdapter(S"select dbms_xmlgen.getxml(' select * from SampleTable') from dual ",myOracleConnection);
myDataSet = new DataSet("Sample");
Sql:
`SqlConnection *mySQLConnection;
SqlDataAdapter * myDataAdapter;
DataSet * myDataSet;
mySQLConnection = new SqlConnection(S"Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw;");
mySQLConnection->Open();
myDataAdapter = new SqlDataAdapter(S"select * from [SampleTable]",mySQLConnection);
myDataSet = new DataSet("Sample");`
i wants to do both connection using one connection object. Is there any idea to achieve this???
I can't give you c++ code, but I can help you how to do it. It will be difficult to do it in one connection, but your can get a DataSet back which will work, and you only have to do the code once.
Create a method will return a DataSet, and pass the query as well as what type of connection should be used, in this method depending on tour connection type you do your query and return your result.
You can also add a connectionstring if you wish.
Something like this (it is c# though)
DataSet GetDataSet(string sqlQuery, ConnectionType connType)
{
DataSet dataset = new DataSet("aDataSet");
using (DataTable table = dataset.Tables.Add("aDataTable"))
{
switch (connType)
{
case ConnectionType.MSSQL:
using (var conn = new SqlConnection("Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw"))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
case ConnectionType.Oracle:
using (var conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw"))
{
using (var cmd = new OracleCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
default:
break;
}
}
return dataset;
}
enum ConnectionType { MSSQL, Oracle }

Fill observableCollection directly from sql server

I would like to know if there is any way to fill ObservableCollection directly from SQL server.
Currently I am loading my data into DataTable (using sqlDataAdapter) and do a conversion to ObservableCollection manually and it very inefficient.
How it can be done?
OK, I have found a way to do this:
It can be done using SqlDataReader.
public ObservableCollection<DataItem> LoadCategoriesData()
{
Command = new SqlCommand(StoredProcedure, Connection);
Command.CommandType = CommandType.StoredProcedure;
ObservableCollection<DataItem> myColl = new ObservableCollection<DataItem>();
Connection.Open();
SqlDataReader reader = Command.ExecuteReader();
while (reader.Read())
{
int mainCatID = reader.GetInt32(0);
string categoryName = reader.GetString(1);
//adding row data to observable
myColl.Add(new DataItem(mainCatID, categoryName));
}
Connection.Close();
return myColl;
}

Resources