I'm trying to get an insert to work using LINQ and am having some difficulties.
I am using this example to base my code: http://msdn.microsoft.com/en-us/library/bb763516.aspx
I have my data object set up, but don't know what's going on when db.Orders.InsertOnSubmit is executed.
How can I create this db object to insert a data object into my database using InsertOnSubmit?
edit: Here is some code that I'm working with (It's probably a world of wrong, I'm pretty much fumbling in the dark at this point). I'm super new to database objects, so the whole concept is a bit confusing for me.
var Data = new Data();
Data.value1 = 1;
var db = new dbo(connectionString);
db.InsertOnSubmit(Data);
You need to do more than just call InsertOnSubmit(). You also need to call SubmitChanges(). The reason these are separate steps is to allow you to have multiple inserts, updates and deletes and then submit them all at once via SubmitChanges().
Related
I am using Entity Framework 6.1.3 connecting to an oracle database.
I am trying to use multiple contexts with the same schemaName for oracle. But when I create the contexts it appears they share the __MigrationHistory table and when the second context attempts to create itself it throws "ORA-00955: name is already used by an existing object". To be clear the two contexts I attempted to split by domain design and do not share any entities between the two.
This is the code I'm attempting to run, and it works fine when I run it against SQL Server. But Oracle throws the ORA-00955 error.
try
{
using (var hContext = new HContextORCL(connectionString, "SchemaName"))
using (var aContext = new AContextORCL(connectionString, "SchemaName"))
{
hContext.Database.Initialize(true);
aContext.Database.Initialize(true);
}
}
I've tried using CreateIfNotExists() instead of the Initialize but receive the same error. I have tried setting both contexts Database.SetInitializer<context>(null); because I don't need the migrations at this point. But that doesn't seem to work either.
Ideally I would like to keep the __MigrationHistory table and have both my contexts initialized in Oracle. But that's not necessary. I can sense myself going off the rails trying to figure out all these work-arounds which when I look at them seem overly complicated for something that works in SQL Server.
I am at a loss how to intialize two contexts with the same schema name in an oracle database.
Alright, for better or worse this is the work around I'm going with. My issue appears to be the MigrationHistory table is shared between the two contexts.
Entity Framework 6 allows you to manipulate the migration table using the System.Data.Entity.Migrations.History namespace (Migrations.History Namespace).
So I open the migrations table, copy all the history rows out, delete the migration table, perform my second context initialization and copy the history rows back into the migration database (created during the second context initialization).
try
{
var dbConnection = new OracleConnection(connectionString);
using (var migrationContext = new Migrations.History.HistoryContext(dbConnection, "SchemaName"))
using (var hContext = new HContextORCL(connectionString, "SchemaName"))
using (var aContext = new AContextORCL(connectionString, "SchemaName"))
{
hContext.Database.Initialize(true);
List<HistoryRow> currentHistory = migrationContext.History.ToList();
migrationContext.Database.Delete();
aContext.Database.Initialize(true);
currentHistory.ForEach(rowItem => migrationContext.History.Add(rowItem));
migrationContext.SaveChanges();
}
}
I'm able to fetch information for whatever table I need the problem here is the update, insert, and delete records, is not working..
I have read the Joomla doc's but even doing the simplest update queries are not working... so here is my code:
UPDATE:
// I'm getting the data from an array
if (!empty($_POST['data'])) {
$getData = json_decode($_POST['data'], true);
}
// after this line I have a foreach for the array
// in the foreach I have a few IF's
// ether if the result from IF is True or False
// in both I have similar queries
// So let say IF return true;
// Lets prepare the Data using OBJECT's
$object = new stdClass();
$object->product_id = $v['product_id'];
$object->product_name = $v['product_name'];
$object->product_price = $v['product_price'];
$object->product_number = $v['product_number'];
$result = JFactory::getDbo()->updateObject('#__tienda_product', $object, 'product_number');
// that should Update my tables but it doesn't ... now my table has about 21 columns
// but I only need to update 4 columns base on the column product_number
You might have notice the $v['product_id'] where $v is from the foreach, the foreach and the first query are working fine, I did a few echo's before moving to the Update part just to make sure I'm getting the correct data in a format that it should be... any way... the Update part is not working... so I thought it may be because of my table I when to use one table from the regular instalation of joomla... but it still the same no result on the update...
Does any one know how to "update" a table using Joomla CMS as framework?...
Remember I want to use the updateObject() method...
Why don't I use Joomla Framework instead of the CMS's library?
Well, I can give you a few examples, let say:
a business man want a simple basic report, he doesn't care about managing the site he has people to do that, he also gets a sales report, but he doesn't trust the crew just yet and he want to able to see and compare the result, and he needs and standalone without all the fancy tools that joomla has and for that he need an standalone app that can give that kind of report... ok I might have gone a bit far, but the idea is to have basic, simple, easy to read reports and updates, and that is why I have started this project.
Again, I already went to joomla and read the docs but following their examples it just not working... now, am I have to declear all of the columns even if they don't need to be update? or am I missing an execution for the query which in joomla doesn't mention any executions when using $object() only when using regular queries SQL... the idea is to use $object() ...
Thank you for taking the time.
You have defined the updateobject as a variable, and are not calling it. try changing this:
$result = JFactory::getDbo()->updateObject('#__tienda_product', $object, 'product_number');
to this:
JFactory::getDbo()->updateObject('#__tienda_product', $object, 'product_number');
Also, on a side note, you should not use $_POST and instead should use JInput
I need to replace EF4.1 with ADO.NET. The data in our application is returned by stored procedures only. I need help re-writing calls like the following (in order to write a DAL for the application):
EF calling stored procedure:
using (var db = new NexGenContext())
{
SqlParameter param = new SqlParameter("#ReviewID", Id);
var issues = db.Database.SqlQuery<QuestionIssue>(
"SP_GetQuestionIssues #ReviewID", param).ToList();
return View(issues);
}
What is the equivalent in ADO.NET? Get data from the database and map to my models?
The closest ADO.NET technology to being an ORM without actually crossing the line is data sets. Data sets act very much like an ORM in the way you can access data directly from a table without looping through a cursor. Data Sets return lists directly and can track new data vs old.
This link is a pretty good overview:
http://www.c-sharpcorner.com/UploadFile/718fc8/working-with-dataset-in-ado-net/
This MVC datasets with viewbags stack thread specifically addresses using Data Sets in Models.
I have a table called Code in my LINQ to SQL datacontext. I also have a class called Codes in my Models folder. What I want to do is save the updated object Codes to my database table Code. Is this possible?
In my controller, I would pass the edited Object to my Model. My CodesRepository file contains this:
public Codes EditCode(Codes CodeToEdit)
{
private EventsDataContext _db = new EventsDataContext();
Codes C = new Codes();
C = CodeToEdit;
_db.Codes.InsertOnSubmit(C); //error here, something about invalid arguments
//InsertOnSubmit is for adding a new object, but I don't know the syntax
// for editing an existing object.
_db.SubmitChanges();
}
This is probably not the correct way of doing this so can someone point me in the right direction? Do I even need a class called Codes or do I need to somehow just use my database table? Thanks.
Solution: I decided to change from Linq to SQL to an Entity Framework and it works much better. This way, I don't have to define my Codes class since it comes straight from the database and I was able to delete the Codes class file.
You should use DataContext.Attach when you get an object back that corresponds to en existing row in the database. For Linq-to-sql's optimistic concurrency handling to work this requires that you either have the original, unsaved object available, or that you have a TimeStamp column in the database. The latter is preferred, as it only requires one extra field to be handled (probably through a hidden field in the web form).
I am using Sql tables without rowversion or timestamp. However, I need to use Linq to update certain values in the table. Since Linq cannot know which values to update, I am using a second DataContext to retrieve the current object from database and use both the database and the actual object as Input for the Attach method like so:
Public Sub SaveCustomer(ByVal cust As Customer)
Using dc As New AppDataContext()
If (cust.Id > 0) Then
Dim tempCust As Customer = Nothing
Using dc2 As New AppDataContext()
tempCust = dc2.Customers.Single(Function(c) c.Id = cust.Id)
End Using
dc.Customers.Attach(cust, tempCust)
Else
dc.Customers.InsertOnSubmit(cust)
End If
dc.SubmitChanges()
End Using
End Sub
While this does work, I have a problem though: I am also using StoredProcedures to update some fields of Customer at certain times. Now imagine the following workflow:
Get customer from database
Set a customer field to a new value
Use a stored procedure to update another customer field
Call SaveCustomer
What happens now, is, that the SaveCustomer method retrieves the current object from the database which does not contain the value set in code, but DOES contain the value set by the stored procedure. When attaching this with the actual object and then submit, it will update the value set in code also in the database and ... tadaaaa... set the other one to NULL, since the actual object does not contain the changed made by the stored procedure.
Was that understandable?
Is there any best practice to solve this problem?
If you make changes behind the back of the ORM, and don't use concurrency checking - then you are going to have problems. You don't show what you did in step "3", but IMO you should update the object model to reflect these changes, perhaps using OUTPUT TSQL paramaters. Or; stick to object-oriented.
Of course, doing anything without concurrency checking is a good way to lose data - so my preferred option is simply "add a rowversion". Otherwise, you could perhaps read the updated object out and merge things... somehow guessing what the right data is...
If you're going to disconnect your object from one context and use another one for the update, you need to either retain the original object, use a row version, or implement some sort of hashing routine in your database and retain the hash as part of your object. Of these, I highly recommend the Rowversion option as well. Using the current value as the original value like you are trying to do is only asking for concurrency problems.