SubmitChanges() doesn't work - c#

I don't know what's wrong with this code , this code compile successfully but doesn't update database . do i miss some thing ?
DataClassesDataContext db = new DataClassesDataContext();
var query = from p in db.AllPatiences
select p;
int newID = 1001;
foreach (AllPatience patient in query)
{
patient.Id = newID.ToString();
newID++;
}
db.SubmitChanges();

My guess is that you're working with a file-based database (.mdf) in your project, and you're trying to look at the table data in that database. When you build your project, the database is cloned into the bin/debug/ or bin/release/ directory, where your running program accesses it. If you take a look at this version of the file, rather than the one you have loaded into your VS project, you should see the changes.
If this is the case, you should set the database file property to "Copy only if newer" or "Do not copy", to avoid it cloning the DB each build.

is patient.Id generated in the database itself? Possibly as an SQL IDENTITY field?
Also, check the SyncOn property of the field in your dbml file.

I found the problem , For Update like that , It's necessary to have primary key . The reason my table didn't have primary key was : I imported those data from an Excel file , So i didn't have Primary key .

Guess, is "Id" your tables primary key? If so, I don't think that L2S supports an update of the primary key (what's very correct in my opinion). You should never attend to change the value of the primary key.
If Id is not your primary key, I have no clue :-P.

Related

Implement an efficent mechanism to check whether a record is referenced in other tables before delete

I am developing an web app using asp.net. I am making this app for compatable for both SQL and MYSQL DB.
So my concern is think that I have a set of records in a table. This table's records are referenced by other tables. So if a user try to delete a record from this table I have to check whether this record is referenced by other tables or not. If not then user can delete the record. I am using using foreign keys for many tables but others not.
So I want this scenario for every tables. So method that coming to my mind is before delete a record I have to run some select queries against those tables to check whether if records available. So is this the only approach.? Seems to its headache. you know if table is referenced by lot of tables. Can I use a flag or some thing?
Is there any better way to do this?
I think this might help you ::
SELECT
table_name, column_name
FROM
information_schema.key_column_usage
WHERE
referenced_table_name = '<table>'
and referenced_column_name = '<primary key column>'
Please check this link too:
MySQL: How to I find all tables that have foreign keys that reference particular table.column AND have values for those foreign keys?
I think it is a little overkill and not performance optimized to be selecting tables and references to check before each delete. You will be making unnecessary database calls.
Since you tag'd ASP.Net are you using ADO ? If so, or similar.
Why not make the normal delete call inside a try block and in the catch handle error message received from database something like:
try
{
}
catch(SqlExcpetion sqlEx)
{
if(sqlEx.Message.ToLower().Contains("foreign"))
{
return "your user friendly error message";
}
}
In case you are using foreign keys to constraint the references, you can act in the following order:
consider you are using database test and are trying to delete a row from emp table
1) list all the tables with their column names, that reference any column in the table we are going to remove a row from (emp in this case)
select
table_name,column_name,referenced_column_name
from
information_schema.KEY_COLUMN_USAGE
where
REFERENCED_TABLE_NAME = 'emp' and REFERENCED_table_schema = 'test';
2) for each row of the result try looking up the value of referenced_column_name from the emp row that is being removed in the corresponding table_name.column_name

Alter column identity with Microsoft.SqlServer.Smo

I've trying to change a column IDENTITY using Microsoft.SqlServer.Smo from a table with no dependencies and with all the data loaded previously (from another DB) but i get an error like this "Modifying the Identity property of the Column object is not allowed. You must drop and recreate the object with the desired property". The thing is that i tried to do this with Management Studio and it has no problem with it. Do you have any suggestions?. Thanks in Advance
This is the code:
foreach (Column source in sourcetable.Columns)
{
try
{
if(source.Identity)
{
Column column = copiedtable.Columns[source.Name];
// column.Computed = source.Computed;
// column.ComputedText = source.ComputedText;
column.Identity = source.Identity;
column.IdentityIncrement = source.IdentityIncrement;
column.IdentitySeed = source.IdentitySeed;
column.Alter();
}
}
catch { }
}
Try doing it in SSMS again and choose to script the action out instead of applying it directly. You'll find that it creates a temporary table with the identity property set to true (and everything else the same), copies your data from the live table into the temp table, drops the live table, and renames the temp table to be the live table. You'll need to do something similar with SMO.
Copying the table is easy enough: iterate over the columns, indexes, foreign keys, etc and create your new table that way (taking care to set the identity property correctly properly before you call Create()). For moving the data, take a look at the Transfer class. Once that's done, it's a drop and rename (or a rename and rename if you want to be safe).
I'm a little surprised that SMO doesn't do this somehow under the covers (since SSMS uses SMO under the covers). If I find something else that makes it do this automatically, I'll let you know.
Are you trying to update an existing record, or add a new record? If you're adding a new record, then do an insert. If you're updating an existing record, don't overwrite the identity column value.
To insert identity values into a table in SQL Server you must tell the database to allow you to do this. Syntax is:
Set Identity_Insert [table] ON
When you're done you need to turn it off again.
Set Identity_Insert [table] OFF

Why isn't the new row being added to my database table?

Here's my code:
private void button1_Click(object sender, EventArgs e)
{
var dbContext = new DataClasses1DataContext();
var record = new AutorizedActivity();
record.MbrId = (int) ddlMember.SelectedValue;
record.ActId = (int) ddlActivity.SelectedValue;
dbContext.AutorizedActivities.InsertOnSubmit(record);
dbContext.SubmitChanges();
}
Basically, the form has two dropdownlists. The user makes a selection from each list and presses the button to update a table with their selections.
The problem is, no data is ever being added to the table. No errors occur at all. I've stepped through in debug, and can't see anything wrong. Are there any common things I could check to determine why the program appears to insert a record, but nothing is actually inserted?
Here's my table definition:
CREATE TABLE [dbo].[AutorizedActivities] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[MbrId] INT NOT NULL,
[ActId] INT NOT NULL,
CONSTRAINT [PK_AutorizedActivities] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_AutorizedActivities_AvailableActivities] FOREIGN KEY ([ActId]) REFERENCES [dbo].[AvailableActivities] ([Id]),
CONSTRAINT [FK_AutorizedActivities_Members] FOREIGN KEY ([MbrId]) REFERENCES [dbo].[Members] ([Id]));
Here's the datacontext layout, for clarity:
SOLUTION: The database table was being updated... just not the one I was looking at. I was running the program in debug mode, which places a copy of the .mdf in the debug/bin directory. I wasn't looking at that table; I was looking at the table in my production directory. If I had ran the program in release mode, it would have worked like a charm and updated the live table, as opposed to the test (debug) version.
Two things might help here, but it's impossible to give a definite answer on this one - you're gonna have to try things. The first things I would try here are changing to the 'standard' structure for EF code, which will "Close/Dispose" the context, and making sure your identity property is set correctly on the Entity itself. Sometimes VS doesn't do that automatically. So, check that setting and change the code to this...
using (var dbContext = new DataClasses1DataContext()) {
var record = new AutorizedActivity();
record.MbrId = (int) ddlMember.SelectedValue;
record.ActId = (int) ddlActivity.SelectedValue;
dbContext.AutorizedActivities.Add(record);
dbContext.SubmitChanges();
}
Also... did you misspell "Authorized" - fix that now before it's too late and you propogate that through the whole app.
The database table was being updated... just not the one I was looking at. I was running the program in debug mode, which places a copy of the .mdf in the debug/bin directory. I wasn't looking at that table; I was looking at the table in my production directory. If I had ran the program in release mode, it would have worked like a charm and updated the live table, as opposed to the test (debug) version.

Entity Framework One-To-Many Insert - Foreign Key violation

I'm using Entity Framework for the first time and I'm trying to create a object with a collection (and I want all the objects in the collection to be created in database as well) but I'm having some foreign keys violations.
My sample tables:
table APPOINTMENTS: ID, VAR1, DATE_APPOINTMENT
table GUESTS: ID, APPOINTMENT_ID, USER_ID, VAR2, VAR3
My test code:
DomainService aux = new DomainService();
APPOINTMENTS appointment = new APPOINTMENTS();
appointment.VAR1 = "BLA";
appointment.DATE_APPOINTMENT = new DateTime();
//The user with id = 1 is already created in the database
appointment.GUESTS.Add(new GUESTS { USER_ID = 1, VAR2 = 1, VAR3 = "F" });
aux.InsertAppointment(appointment);
At DomainService I have:
public void InsertAppointment(APPOINTMENTS appointment)
{
using (var context = this.ObjectContext)
{
context.AddToAPPOINTMENTS(appointment);
context.SaveChanges();
}
}
But I'm getting this error:
{"ORA-02291: integrity constraint (FK_GUESTS_APPOINTMENTS) violated - parent key not found"}
What am I doing wrong?
UPDATE:
To create the ID's in the database, I am using a sequence for each table and a trigger before insert to get the next value.
When I create a single object, e.g. a appointment without guests, it inserts in the database and it generates the id.
The solution to this problem:
"The ID fields that are generated from sequences won't be handled
correctly. After saving the entities the ID's will be returned as 0.
I'll fix this by manually hacking the SSDL (open your .edmx file in a
text editor) with StoreGeneratedPattern="Identity" attributes on the
ID fields (lines 6 and 16). Note that designer may rip that change out
upon future modification.
While I suppose it's not absolutely necessary it might also be prudent
to modify some type metadata such as changing "number"s to "int"s in
your SSDL and "Decimal"s to "Int32"s in your CSDL where applicable.
Frequently these don't auto-generate with the desired values
especially with XE."
#http://www.chrisumbel.com/article/oracle_entity_framework_ef
As for me, the problem was solved simply by opening diagram .edmx and changing property StoreGeneratedPattern from None to Identity for each Primary Key in each table. After saving everything was fine.
I'm using VS 2012, Entity Framework 5 (6 is not supported yet), Oracle 11.2, last ODP.NET 12, .Net 4.5
In case of EF code first approach, if this error come
(ORA-02291: integrity constraint (FK_GUESTS_APPOINTMENTS) violated -
parent key not found)
In my case there are 2 tables which have Identity columns. So I just added
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
property to my model class just above the the column which is identity column in database and it solved my problem :)
Hope this help :)
I cant see where you are setting your Primary Key (the ID property of the appointment class). Are you using a key generator on the database side? If not this should be the problem.
You're inserting a record with a foreign key value that is not found in the parent table that constraint refers back to.

Entity Framework Invalid Object Name Error

I'm using VS2008 to connect to a SQL server database in order to populate it in C#. It's going pretty well, I'm able to query, insert, and update all tables in my database successfully, except one. Anytime I try to query or insert into one table I get the following error:
Message = "Invalid object name 'DB_NewModelStoreContainer.DATATYPE'."
the query that generated this error is:
var test3 = (from o in context.DATATYPE
where o.DATETYPE_NAME == "Single"
select o).First();
(yes I know it should be DATATYPE, but that is not the problem =) )
Whenever I added the database to my project, for some reason it marked every attribute in the DATATYPE table as a primary key. I went into the xml of the .edmx and fixed this but I still get this error and I cannot find out why ><. Any help at all would be very greatly appreciated! Thanks in advance.
In order to work with EntityFramework ,there should be clearly mentioned PrimaryKey and Foreign Key if any exists.
If you don't have any primary Key ,make the unique column as primary key ,It should definately work. and I am wondering how could you are able to insert record without primary key
in edmx designer you might have misssed something or may be some mapping got screwed up after changes.so,modify the tables in your database to asign the primary key to every table and then try to generate the edmx from scratch.

Categories

Resources