Oracle columns update not happpening - sql

I am trying to update a few columns in a Oracle table from my C# code.
Here is my method:
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
whereClause = String.Format(whereClause, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), whereClause);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
Here is the Query:
UPDATE
{0}
SET
SYNC_STATUS = '{1}'
,SYNC_DATE = TO_DATE('{2}', 'yyyy/mm/dd')
{3}
And the where clause will look something like:
WHERE ID = {0}
This method updates about 10 records, and the rest stays null. This mehod does return true, and I have debugged, no exception is thrown.
Why does it not update all records?

This isn't an answer but might help debug the problem.
Instead of the like:
cmd.ExecuteNonQuery();
put in this:
int count = cmd.ExecuteNonQuery();
if (count == 0)
{
Console.WriteLine("");
}
Put a break on the Console.WriteLine("") and run it. The debugger will stop if no rows were updated. You can then check the query, and whether or not that ID actually exists.

The problem was with the WHERE clause. Since it contains a place holder {0}, after I I formatted the WHERE clause, the ID always stayed to the value it was formatted with first.
This is what my new method looks like.
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
string originalWhere = whereClause;
originalWhere = String.Format(originalWhere, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), originalWhere);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
bool success = cmd.ExecuteNonQuery() > 0;
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
As can be seen, I added a variable 'originalWhere', that gets formatted, but most importantly, is being set to original WHERE clause parameter passed, so that it will always contain the place holder.

Related

Google BigQuery returns only partial table data with C# application using .net Client Library

I am trying to execute the query (Basic select statement with 10 fields). My table contains more than 500k rows. C# application returns the response with only 4260 rows. However Web UI returns all the records.
Why my code returns only partial data, What is the best way to select all the records and load into C# Data Table? If there is any code snippet it would be more helpful to me.
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
using System.Security.Cryptography.X509Certificates;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
try
{
Console.WriteLine("Start Time: {0}", DateTime.Now.ToString());
String serviceAccountEmail = "SERVICE ACCOUNT EMAIL";
var certificate = new X509Certificate2(#"KeyFile.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { BigqueryService.Scope.Bigquery, BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.CloudPlatform, BigqueryService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "PROJECT NAME"
});
string query = "SELECT * FROM [publicdata:samples.shakespeare]";
JobsResource j = Service.Jobs;
QueryRequest qr = new QueryRequest();
string ProjectID = "PROJECT ID";
qr.Query = query;
qr.MaxResults = Int32.MaxValue;
qr.TimeoutMs = Int32.MaxValue;
DataTable DT = new DataTable();
int i = 0;
QueryResponse response = j.Query(qr, ProjectID).Execute();
string pageToken = null;
if (response.JobComplete == true)
{
if (response != null)
{
int colCount = response.Schema.Fields.Count;
if (DT == null)
DT = new DataTable();
if (DT.Columns.Count == 0)
{
foreach (var Column in response.Schema.Fields)
{
DT.Columns.Add(Column.Name);
}
}
pageToken = response.PageToken;
if (response.Rows != null)
{
foreach (TableRow row in response.Rows)
{
DataRow dr = DT.NewRow();
for (i = 0; i < colCount; i++)
{
dr[i] = row.F[i].V;
}
DT.Rows.Add(dr);
}
}
Console.WriteLine("No of Records are Readed: {0} # {1}", DT.Rows.Count.ToString(), DateTime.Now.ToString());
while (true)
{
int StartIndexForQuery = DT.Rows.Count;
Google.Apis.Bigquery.v2.JobsResource.GetQueryResultsRequest SubQR = Service.Jobs.GetQueryResults(response.JobReference.ProjectId, response.JobReference.JobId);
SubQR.StartIndex = (ulong)StartIndexForQuery;
//SubQR.MaxResults = Int32.MaxValue;
GetQueryResultsResponse QueryResultResponse = SubQR.Execute();
if (QueryResultResponse != null)
{
if (QueryResultResponse.Rows != null)
{
foreach (TableRow row in QueryResultResponse.Rows)
{
DataRow dr = DT.NewRow();
for (i = 0; i < colCount; i++)
{
dr[i] = row.F[i].V;
}
DT.Rows.Add(dr);
}
}
Console.WriteLine("No of Records are Readed: {0} # {1}", DT.Rows.Count.ToString(), DateTime.Now.ToString());
if (null == QueryResultResponse.PageToken)
{
break;
}
}
else
{
break;
}
}
}
else
{
Console.WriteLine("Response is null");
}
}
int TotalCount = 0;
if (DT != null && DT.Rows.Count > 0)
{
TotalCount = DT.Rows.Count;
}
else
{
TotalCount = 0;
}
Console.WriteLine("End Time: {0}", DateTime.Now.ToString());
Console.WriteLine("No. of records readed from google bigquery service: " + TotalCount.ToString());
}
catch (Exception e)
{
Console.WriteLine("Error Occurred: " + e.Message);
}
Console.ReadLine();
}
}
}
In this Sample Query get the results from public data set, In table contains 164656 rows but response returns 85000 rows only for the first time, then query again to get the second set of results. (But not known this is the only solution to get all the results).
In this sample contains only 4 fields, even-though it does not return all rows, in my case table contains more than 15 fields, I get response of ~4000 rows out of ~10k rows, I need to query again and again to get the remaining results for selecting 1000 rows takes time up to 2 minutes in my methodology so I am expecting best way to select all the records within single response.
Answer from User #:Pentium10
There is no way to run a query and select a large response in a single shot. You can either paginate the results, or if you can create a job to export to files, then use the files generated in your app. Exporting is free.
Step to run a large query and export results to files stored on GCS:
1) Set allowLargeResults to true in your job configuration. You must also specify a destination table with the allowLargeResults flag.
Example:
"configuration":
{
"query":
{
"allowLargeResults": true,
"query": "select uid from [project:dataset.table]"
"destinationTable": [project:dataset.table]
}
}
2) Now your data is in a destination table you set. You need to create a new job, and set the export property to be able to export the table to file(s). Exporting is free, but you need to have Google Cloud Storage activated to put the resulting files there.
3) In the end you download your large files from GCS.
It my turn to design the solution for better results.
Hoping this might help someone. One could retrieve next set of paginated result using PageToken. Here is the sample code for how to use PageToken. Although, I liked the idea of exporting for free. Here, I write rows to flat file but you could add them to your DataTable. Obviously, it is a bad idea to keep large DataTable in memory though.
public void ExecuteSQL(BigqueryService bqservice, String ProjectID)
{
string sSql = "SELECT r.Dealname, r.poolnumber, r.loanid FROM [MBS_Dataset.tblRemitData] R left join each [MBS_Dataset.tblOrigData] o on R.Dealname = o.Dealname and R.Poolnumber = o.Poolnumber and R.LoanID = o.LoanID Order by o.Dealname, o.poolnumber, o.loanid limit 100000";
QueryRequest _r = new QueryRequest();
_r.Query = sSql;
QueryResponse _qr = bqservice.Jobs.Query(_r, ProjectID).Execute();
string pageToken = null;
if (_qr.JobComplete != true)
{
//job not finished yet! expecting more data
while (true)
{
var resultReq = bqservice.Jobs.GetQueryResults(_qr.JobReference.ProjectId, _qr.JobReference.JobId);
resultReq.PageToken = pageToken;
var result = resultReq.Execute();
if (result.JobComplete == true)
{
WriteRows(result.Rows, result.Schema.Fields);
pageToken = result.PageToken;
if (pageToken == null)
break;
}
}
}
else
{
List<string> _fieldNames = _qr.Schema.Fields.ToList().Select(x => x.Name).ToList();
WriteRows(_qr.Rows, _qr.Schema.Fields);
}
}
The Web UI automatically flattens the data. This means that you see multiple rows for each nested field.
When you run the same query via the API, it won't be flattened, and you get fewer rows, as the nested fields are returned as objects. You should check if this is the case at you.
The other is that indeed you need to paginate through the results. Paging through list results has this explained.
If you want to do only one job, than you should write your query ouput to a table, than export the table as JSON, and download the export from GCS.

Deleting the last row in a table. SQL/Netbeans

In java, i am trying to delete the last row of my database. The database has 15 rows and i want to the delete the 15th one. The columns are called Initials and Score.
Intials Scores
rows# 1. ADS 2343
2. DDE 5454
15. TBK 332
I can't have it selecting TBK because i'm wanting it to delete the 15th one no matter what it is so a new one can be added. Everywhere I've looked it's always has to be specific or a delete all rows. Can anyone help? Many thanks to those who help. :)
Assuming id is an identity column
DELETE FROM table
WHERE id = (SELECT MAX(id) FROM table)
OP : I am trying to delete the last row of my database.
make resultset updatable : ResultSet.CONCUR_UPDATABLE);
set cursor to last record : resultSet.last();
delete last Record : resultSet.deleteRow();
for further use of rs you should set : resultSet.beforeFirst();
private static int delLastRow(ResultSet resultSet) {
if (resultSet == null) {
return 0;
}
try {
resultSet.last();
int delID = resultSet.getInt(1);
resultSet.deleteRow();
System.out.println("Deleted id :" + delID);
resultSet.beforeFirst();
return delID;
} catch (SQLException exp) {
exp.printStackTrace();
} finally {
try {
resultSet.beforeFirst();
} catch (SQLException exp) {
exp.printStackTrace();
}
}
return 0;
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//rs will be scrollable, will not show changes made by others,
//and will be updatable
String sql;
sql = "SELECT * FROM `order details`";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("Deleted id :"+ delLastRow(rs));
....
}

Using C# remove unnecessary “TABLE_NAME” from Excel worksheets

Can anyone tell me, I am going to upload excel file, this file has unnecessary table like "_xlnm#Print_Titles" that I need to remove or delete that field. This a my method. But it is does not work for remove or delete.
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if ((dt == null) )
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
if ((excelSheetNames[i].Contains("_xlnm#Print_Titles") || (excelSheetNames[i].Contains("Print_Titles"))))
{
if (true)
{
row.Table.Rows.Remove(row);
dt.AcceptChanges();
}
}
i++;
}
return excelSheetNames;
}
Instead of removing items in the foreach loop, we'll find them and add them to a list, then we'll go through that list and remove them from your data table.
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if ((dt == null))
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
var rowsToRemove = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
var row = dt.Rows[i];
excelSheetNames[i] = row["TABLE_NAME"].ToString();
if ((excelSheetNames[i].Contains("_xlnm#Print_Titles") || (excelSheetNames[i].Contains("Print_Titles"))))
{
rowsToRemove.Add(dt.Rows[i]);
}
i++;
}
foreach (var dataRow in rowsToRemove)
{
dt.Rows.Remove(dataRow);
}
return excelSheetNames;
}
Those _xlnm and "$" are sheets that, turns out, shouldn't be normally accessed by the users.
You can solve this in 2 ways.
Ignore them
Drop them
The former is highly recommended.
To do this you need to use the following code:
if (!dt.Rows[i]["Table_Name"].ToString().Contains("FilterDatabase") && !dt.Rows[i]["Table_Name"].ToString().EndsWith("$'"))
{
}
You can either use .Contains() and/or .EndsWith() to filter out those sheets.

using clearParameter() even thought PreparedStatement is being closed

private PreparedStatement InsertPS = null;
public boolean InsertInDB(String username, String password, double balance, String secret) {
boolean ans = false;
try {
InsertPS = con.prepareStatement("Insert into BankDB values(?,?,?,?)");
String data[] = AMC.SendtoDB(password, secret);
InsertPS.setString(1, data[0]);
InsertPS.setString(2, username);
InsertPS.setString(3, data[1]);
InsertPS.setDouble(4, balance);
int rows = InsertPS.executeUpdate();
if (rows != 0) {
ans = true;
}
InsertPS.clearParameters();
} catch (SQLException sqlInite) {
System.out.println("SQL Error in InsertInDB method: " + sqlInite);
} finally {
try {
InsertPS.close();
} catch (SQLException sqle) {
System.out.println("SQL Exception in InsertInDB method finally clause : " + sqle);
}
}
return ans;
}
Above is the InsertInDB() method given,
It has a InsertPS PreparedStatement Object.
Here is it necessary to use clearParameters() method even though i am closing the InsertPS object at the end of the method.
(I have provided a separate method to close the connection object)
also another question: Is it a good idea to create PreparedStatement Object's outside any method within a class,initializing using Constructor and Say for example Once all Object's (each in different method) are used, close all PreparedStatement Objects using a separate method.
public class JavatoDB {
Driver DM = null;
Connection con = null;
PreparedStatement InsertPS = null;
PreparedStatement BalancePS = null;
PreparedStatement DeletePS = null;
PreparedStatement UpdatePS = null;
PreparedStatement SearchDB = null;
ResultSet RS = null;
ResultSetMetaData RSMD = null;
AdminControl AMC = null;
public JavatoDB() {
AMC = new AdminControl();
try {
DM = new com.mysql.jdbc.Driver();
con = DriverManager.getConnection("jdbc:mysql://localhost/javadb", "java", "javaaccess");
InsertPS = con.prepareStatement("Insert into BankDB values(?,?,?,?)");
BalancePS = con.prepareStatement("Select BALANCE from BankDB where ACCNAME=? AND ACCPIN = ?");
DeletePS = con.prepareStatement("Delete from BankDB where ACCNAME = ? AND ACCPIN = ? ");
UpdatePS = con.prepareStatement("Update BankDB set BALANCE = (BALANCE + ?) where ACCNAME = ? AND ACCPIN = ?");
SearchDB = con.prepareStatement("Select ID AND ACCPIN from BankDB where ACCNAME = ? ");
} catch (SQLException JavatoDBContrsuctor) {
System.out.println("SQL Error in JavatoDBConstructor: " + JavatoDBContrsuctor);
}
}
public boolean InsertInDB(String username, String password, double balance, String secret) {
boolean ans = false;
try {
String data[] = AMC.SendtoDB(password, secret);
InsertPS.setString(1, data[0]);
InsertPS.setString(2, username);
InsertPS.setString(3, data[1]);
InsertPS.setDouble(4, balance);
int rows = InsertPS.executeUpdate();
if (rows != 0) {
ans = true;
}
InsertPS.clearParameters();
} catch (SQLException sqlInite) {
System.out.println("SQL Error in InsertInDB method: " + sqlInite);
}
return ans;
}
Suggestion's or Criticism on other aspects of code are also welcome.
For the first question, when you call:
con.prepareStatement()
a new preparedStatement is created, then parameters dont survive, i mean you dont need to clear then.
About the second question, in your implementation i cant see where you close your preparedStatement, and if you only add close, next time method will fail. Then, it is usual to create the preparedStatement and close it in the same method.

How to create a new table in a database with program that uses entity framework?

I have a piece of software out in the field and I need to add a new table to it. I have the table in my entity framework and new clients get the table. How to I update the others?
ADDED: To make it clear my development and new clients have the table. How to update the older clients databases is the question?
Since it is in my model it seems I should just call a create method and everything should happen under the hood.
_context.NewTable.CreateTable();
But think that I will have to write a sql command string to see if table exists and if it doesn't to create the table.
IDVisitorEntities _context = new IDVisitorEntities ();
String cmd = IF NOT EXISTS ( SELECT [name]
FROM sys.tables
WHERE [name] = NewTable )
CREATE TABLE NewTable (
ID int IDENITY,
NAME VARCHAR(40))
_context.NewTable.CommandText (cmd);
I want to only run this one time if the table doesn't exist. So that doesn't solve that problem. I really don't know what to do.
ADDED 5/6/2013
I'm thinking that EF has the Property Collection for each table and that might hold a clue. Might have to use ICustomTypeDescriptor ... Anyone else have any thoughts?
Added 7/15/2013
I started building it, at my new job, here is a sample. I need to create a file(s) with the partial classes and have the abstract and interface applied to them. It has a long way to go but this is a start...
namespace DataModelMAXFM
{
public abstract class ATable
{
private ArrayList _columns = new ArrayList();
private ArrayList colsToAdd = new ArrayList();
public ArrayList Columns
{
get
{
return _columns;
}
}
public bool TableCreate(SqlConnection sqlConn)
{
//assuming table needs to be created (already checked)
//get column list
//use for loop to create query string
// run command
ITable thisItable;
if (Columns.Count <= 0) //generate column list if not already created
{
if (!ColumnList())
return false;
}
if (this is ITable)
{
thisItable = (ITable) this;
}
else
{
throw new Exception("");
}
StringBuilder sb = new StringBuilder("CREATE TABLE " + thisItable.GetTableName() + " (");
bool flgFirst = true; // to allow for proper comma placement
foreach (PropertyInfo prop in Columns)
{
String propType = this.GetDataType(prop);
if (propType == String.Empty)//check to make sure datatype found a match, EF to SQL
{
return false;
}
if (!flgFirst)
{
sb.Append(", ");
}
else
{
flgFirst = false;
}
sb.Append(prop.Name + " " + propType);
}
// add right parentheses
sb.Append(")");
//now run query created above
SqlCommand com;
try
{
com = new SqlCommand(sb.ToString(), sqlConn);
com.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine("TableCreate e:" + e.ToString());
return false;
}
return true;
}
public bool TableExists(SqlConnection sqlConn)
{
SqlDataReader sdr = null;
SqlCommand com;
ITable thisItable;
try
{
//create and execute command
if (this is ITable)
thisItable = (ITable)this;
else
{
throw new Exception("");
}
com = new SqlCommand("Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = " + thisItable.GetTableName(), sqlConn);
sdr = com.ExecuteReader();
if (!sdr.HasRows)//ie table does not exist
{
return false;
}
}
catch (Exception e)
{
Console.WriteLine("TableCreate e:" + e.ToString());
return false;
}
//close datareader
try
{
sdr.Close();
}
catch (Exception e)
{
Console.WriteLine("close sqldatareader TableExists e: " + e.ToString());
}
return true;
}
public bool ColumnList()
{
bool flgListCreated = false;
PropertyInfo[] propList = typeof(TransactionCategory).GetProperties();
foreach (PropertyInfo prop in propList)
{
if (prop.CanRead && prop.CanWrite)
{
MethodInfo mget = prop.GetGetMethod(false);
MethodInfo mset = prop.GetSetMethod(false);
// Get and set methods have to be public
if (mget == null)
{
continue;
}
if (mset == null)
{
continue;
}
Columns.Add(prop);
if (!flgListCreated)
{
flgListCreated = true;
}
}
}
return flgListCreated;
}
public bool ColumnsExist(SqlConnection sqlConn)
{
ITable thisItable;
if (Columns.Count <= 0)
{
if (!ColumnList())
return false;
}
//2013-07-10 create basic connection and data reader
if (this is ITable)
thisItable = (ITable)this;
else
{
throw new Exception("");
}
SqlDataReader sdr = null;
SqlCommand com;
foreach (PropertyInfo prop in Columns)
{
try
{
//create and execute command
com = new SqlCommand("Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = " + thisItable.GetTableName() + " and COLUMN_NAME = " + prop.Name, sqlConn);
sdr = com.ExecuteReader();
//if no rows returned to datareader == column does not exist, add to ArrayList of columns to add
if (!sdr.HasRows)
colsToAdd.Add(prop);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
}
//close datareader
try
{
sdr.Close();
}
catch (Exception e)
{
Console.WriteLine("close sqldatareader ColumnsExist e: " + e.ToString());
}
if (colsToAdd.Count == 0)
return false;
//returns true only if method worked and found columns to add to DB
return true;
}
public bool ColumnsCreate(SqlConnection sqlConn)
{
ITable thisItable;
StringBuilder sb = new StringBuilder();
if (colsToAdd.Count <= 0)
{
if (!ColumnsExist(sqlConn)) //2013-07-08 - MAXIMUS\58398(BJH) //if no columns, attempt to create list
return false; // if Column list was not created, return false
}
// add a array of the alter table
if (this is ITable)
thisItable = (ITable)this;
else
{
throw new Exception();
}
sb.Append("ALTER TABLE " + thisItable.GetTableName() + " ADD ( ");
bool flgFirst = true; // allows for no leading comma on first entry
String propType;
foreach (PropertyInfo prop in colsToAdd)
{
//make sure SQL datatype can be determined from EF data
propType = this.GetDataType(prop);
if (propType == String.Empty)
throw new Exception("no datatype match found " + prop.Name + " " + prop.PropertyType.ToString());
if (!flgFirst)
{
sb.Append(", ");
}
else
{
flgFirst = false;
}
sb.Append(prop.Name + " " + propType);
}
sb.Append(" )");
SqlCommand com;
try
{
com = new SqlCommand(sb.ToString(), sqlConn);
com.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
return true;
}
public bool ColumnsUpdate(SqlConnection sqlConn)
{
if (ColumnsExist(sqlConn))
return ColumnsCreate(sqlConn);
else
return false;
}
//method to convert from EF to SQL datatypes, see noted issues
public String GetDataType(PropertyInfo pi)
{
String s = "";
String pistr = pi.PropertyType.ToString();
switch (pistr)
{
case "Byte[]":
s = "binary";
break;
case "Boolean":
s = "bit";
break;
case "String Char[]": // also maps to other options such as nchar, ntext, nvarchar, text, varchar
s = "char";
break;
case "DateTime":
s = "datetime";
break;
case "DateTimeOffset":
s = "datetimeoffset";
break;
case "Decimal":
s = "decimal";
break;
case "Double":
s = "float";
break;
case "Int16":
s = "smallint";
break;
case "Int32":
s = "int";
break;
case "Int64":
s = "bigint";
break;
case "Single":
s = "real";
break;
case "TimeSpan":
s = "time";
break;
case "Byte":
s = "tinyint";
break;
case "Guid":
s = "uniqueidentifier";
break;
case "Xml":
s = "xml";
break;
default:
Console.WriteLine("No datatype match found for " + pi.ToString() + " " + pi.PropertyType.ToString());
return String.Empty;
}
return s;
}
}
public interface ITable
{
int ID
{
get;
}
bool TableUpdate(SqlConnection sqlConn);
bool TableStoredProceduresCreate(SqlConnection sqlConn);
bool TableStoredProceduresDrop(SqlConnection sqlConn);
bool TableCreateTriggers(SqlConnection sqlConn);
bool TableCreateViews(SqlConnection sqlConn);
DataTable GetDataTable();
DateTime dtTableImplemented
{
get;
}
String GetTableName();
}
}
How to I update the others?
And how do you upgrade code of others to require that table? Probably by using some patch or upgrade package and this package should create your table as well.
Since it is in my model it seems I should just call a create method and everything should happen under the hood.
No. EF itself has nothing to define database schema (Except creating SQL script for whole database creation). What you are looking for is possible with EF Migrations but that is feature of EF 4.3 and newer when using code first and DbContext API.