I'm new to Dapper and currently I'm trying to populate my fresh database.
Since Dapper has no ability to create a table from model directly, how should I populate my database? Are there any good practices other than executing a schema from the variable?
Currently, I'm using this (dirty approach):
public void CreateTables()
{
using (var connection = GetSQLiteHandle())
{
string sql = #"
CREATE TABLE IF NOT EXISTS statistics (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
content TEXT NOT NULL,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS names (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
username TEXT NOT NULL,
email TEXT NOT NULL,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS storage (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL
);
";
connection.Execute(sql);
}
}
Dapper has no ability to generate tables like Entity Framework. Hence, you may use EF with code first approach. If you want to use Dapper, you can use migrator tools such as fluent migrator and generate db with it.
Related
I can't insert row into database. I'm using .NET with Oracle. I can insert rows to another tables but I can't insert to m:n table, that has two FKeys.
public static String SQL_INSERT = "INSERT INTO UserBet(bet_id, ticket_id) VALUES(:bet_id, :ticket_id)";
public static int Insert(int ticket_id, int bet_id, OracleDB pDb = null)
{
OracleDB db;
if (pDb == null)
{
db = new OracleDB();
db.Connect();
}
else
{
db = pDb;
}
OracleCommand command = db.CreateCommand(SQL_INSERT);
command.Parameters.Add(":bet_id", 1);
command.Parameters.Add(":ticket_id", 1);
int ret = db.ExecuteNonQuery(command);
if (pDb == null)
{
db.Close();
}
return ret;
}
The table UserBet is:
CREATE TABLE userbet
(
bet_id INTEGER NOT NULL,
ticket_id INTEGER NOT NULL
);
ALTER TABLE userbet
ADD CONSTRAINT userbet_pk
PRIMARY KEY (bet_id, ticket_id);
ALTER TABLE userbet
ADD CONSTRAINT userbet_bet_fk
FOREIGN KEY (bet_id) REFERENCES bet (bet_id);
ALTER TABLE userbet
ADD CONSTRAINT userbet_ticket_fk
FOREIGN KEY (ticket_id) REFERENCES ticket (ticket_id);
This doesn't work and I got no error messages. How I said, other inserts are working just this doesn't. It's M:N table. Any hint please?
EDIT: It turns out that the problem was caused by the constraints.
If there is a table t1 and another table t2, where t1.key is a foreign key referencing t2, then, to protect data integrity, Oracle enforces the foreign key as a constraint, that is, you cannot insert into a table a record having a foreign key pointing to a not existent record. You cannot update a foreign key to a value that does not exist. You cannot delete a record from the main table without handling this in some manner in the reference table(s). You can define cascade as the on delete action for instance.
From the above, an exception is null. If your field is nullable, then it can be null, even though that's certainly not a value for the primary key in the referenced table. It's logical though, since null is the lack of a value and therefore it's not a reference.
I am trying to locate a filed in my database table. I done this successfully with tables that just required one key to find, however this table has a composite key attached to it so I have to use the following code to pass in the two keys
//Saving quantity edits
// Create an array for the key values to find.
object[] findTheseVals = new object[2];
// Set the values of the keys to find.
findTheseVals[0] = int.Parse(cbo_OrderID.Text);
findTheseVals[1] = int.Parse(txt_orderitemIDtext.Text);
drOrderEdit = dsOrderItem.Tables["OrderItem"].Rows.Find(findTheseVals);
It accepts the two keys as i am no longer getting an error saying something along the lines of 'expecting two keys only received one' the crash happens at the next line of code where I get an 'object is not set to an instance of an object' error
//Error is at this begin edit statement
drOrderEdit.BeginEdit();
drOrderEdit["Quantity"] = txt_editquantity.Text;
drOrderEdit.EndEdit();
daEditOrderItem.Update(dsOrderItem, "OrderItem");
Why isn't the Datarow being set? the two values that are assigned to the object array are values that that are contained in the primary key and composite key columns.
Here's the script for the creation of the table concerned:
Create Table OrderItem
(
OrderItemID int not null,
OrderID int not null,
Quantity smallint not null,
ProductID INT not null,
CHECK (Quantity > 0 AND Quantity < 51),
CONSTRAINT PK_OIOrderID PRIMARY KEY (OrderID,ProductID),
CONSTRAINT FK_Prod FOREIGN KEY (ProductID)
REFERENCES Product(ProductID)
on delete cascade,
CONSTRAINT FK_Order foreign key (OrderID)
REFERENCES ORDERS (OrderID)
on delete cascade
)
So it looks like my script was set up incorrectly.
The line
CONSTRAINT PK_OIOrderID PRIMARY KEY (OrderID,ProductID),
Should have been
CONSTRAINT PK_OIOrderID PRIMARY KEY (OrderItemID,OrderID),
Made these changes, and the edits were accepted.
For example, I have the following Table:
CustomerInfo
cus_id: auto increment, int, is Identity
cus_name: nvarchar
If I use the follow codes to insert the record "Peter",
string name = "Peter";
DataContext DC = new DataContext();
CustomerInfo newCustomer = new CustomerInfo();
newCustomer.cus_name = name;
DC.CustomerInfos.InsertOnSubmit(newCustomer);
DC.SubmitChanges();
The following error returns,
Can't perform Create, Update, or Delete operations on 'Table(CustomerInfo)' because it has no primary key.
Do I need to self-define the cus_id or any other solutions? Thanks!
First of all LINQ-To-SQL needs primary keys in order to be able to do Inserts and Updates, so you probably have to add the Primary Key in your table.
Now, because it is an auto incremented identity column, in your dbml, you have to select the column "cus_id" of the "CustomerInfo" table and go to the properties and set the following:
Auto Generated Value : True
Auto-Sync : OnInsert
This will ensure that when you insert a new row it will get a new id.
naratting from answer 1 of question you'll have to make cus_id as primary key too.
you can also try to do following
CREATE TABLE Customers
(
cus_id int NOT NULL AUTO_INCREMENT,
cus_name varchar(255) NOT NULL,
PRIMARY KEY (cus_id)
)
I got this error to. As far as I manged to fix it was to add a primary key.
This code made me a primary key and made it autoincrement. Maybe it's what you are looking for?
(When you create the table)
columnname bigint IDENTITY(1,1) NOT NULL,
CONSTRAINT pkcolumnname PRIMARY KEY CLUSTERED
I am sure m missing something really small but i am having issue of Primary value auto incremental. I have creates two simple table and I have adopt Existing database model first approach by using Entity Framework 5. I simple adding values in table from console program.
My issue is code works fine for first time, but crashes if i try to add more value by running whole app again and i found the reason; the EF doesn't increment primary index automatically.
table
CREATE TABLE [dbo].[Book_Titles] (
[Book_ID] INT NOT NULL,
[Title] NVARCHAR (150) NOT NULL,
PRIMARY KEY CLUSTERED ([Book_ID] ASC)
);
CREATE TABLE [dbo].[Books_Authors] (
[Author_Id] INT NOT NULL,
[Author_Name] NVARCHAR (150) NOT NULL,
[Book_ID] INT NULL,
PRIMARY KEY CLUSTERED ([Author_Id] ASC),
FOREIGN KEY ([Book_ID]) REFERENCES [dbo].[Book_Titles] ([Book_ID])
);
Console program
namespace Database_First_01
{
class Program
{
static void Main(string[] args)
{
using (var db = new BooksContext())
{
var book = new Book_Titles()
{
Title ="EF ",
};
var author = new Books_Authors()
{
Author_Name = "me!",
};
book.Books_Authors.Add(author);
db.Book_Titles.Add(book);
db.SaveChanges();
}
}
}
}
many thanks in advance.
Try this
CREATE TABLE [dbo].[Book_Titles] (
[Book_ID] INT IDENTITY(1,1) NOT NULL,
[Title] NVARCHAR (150) NOT NULL,
PRIMARY KEY CLUSTERED ([Book_ID] ASC)
);
Define Identity on Column
Same as other if you want.
Microsoft SQL Server uses the IDENTITY keyword to perform an auto-increment feature. and its missing in your case.
You can use IDENTITY property in different cases
Its used with the CREATE TABLE
and ALTER TABLE Transact-SQL statements.
so if you have already created the table ( and it has data ) you may just alter like as follow.
ALTER TABLE (yourTable) ADD NewColumn INT IDENTITY(1,1)
ALTER TABLE (yourTable) DROP COLUMN OldColumnName
sp_rename 'yourTable.NewColumn', 'OldColumnName', 'COLUMN'
and it will save your data in the existing table.
Hope it will help
Is it possible to update a primary key after it's been created in SubSonic 3.0??
Consider this MySql table:
create table items (
Type varchar(30) NOT NULL,
Attribute varchar(30) NOT NULL PRIMARY KEY);
And I am trying to edit an item object (so called row)
item i = item.SingleOrDefault(i => i.Attribute == "123");
i.Attribute = "234";
i.Save();
The above snippet throws a syntax error MySQLException. After profiling the same, the query that was being executed at back end was this:
UPDATE ITEMS WHERE ATTRIBUTE="123";
Any suggestions/help please.