EntitySet<T> in LINQ to SQL- using it and removing it - c#

I've got a pair of tables in my database. One of which has a primary key (a simple numerical ID), the other has that ID as a foreign key.
The first table has suddenly gained an EntitySet<OtherTable>. If I add a new OtherTable() to this, is it automatically sent to the database, and the ID's linked up, etc, when I use SubmitChanges()?
Secondly, the relationship isn't many-to-one, it's one-to-one, a corresponding entry in the second table is optional and singular. As such, a container like EntitySet isn't really appropriate for this relationship. An OtherTable? would be a more appropriate representation. How can I inform LINQ to SQL of this?

Set Unique = true in the associaton properties. That should adjust it to being 1:1

Related

Checking for duplicate rows using Entity Framework in C#

Using Entity Framework 6.x. For some entities after I create a new instance of an entity object and populate it with data values, I would then like to be able to trigger a lookup on the database. I would like to see if a row exists with all the same values that where populated into the entity object and if it exists return the primary key.
It seems logical that there should be a standard way to do this built into the entity framework but I can't find it. It would be nice if there was a method that would just take any entity object and return the primary keys of any matching rows.
What's wrong with just doing a FirstOrDefault() filter to retrieve an entity with matching values?
var entity = new Entity { // initialize some properties }
var matched = dbContext.EntityTable.FirstOrDefault(x => x.PropA = entity.PropA && x.PropB = entity.PropB);
(Don't have EF on my machine right now, the actual access code is just psuedo)
This is not possible. You have to create query with all data values that you want to check. Another option is to have checksum column that contains some hash from all values (without the primary key), then you can compute the hash from newly created entity and query database if entity with such hash exist.
Edit: Additionaly there is an option to create multi column Constraint in SQL Server (check this: Unique constraint on multiple columns), but it doesn't return primary key of duplicated row in a convenient way.

Implement a "One-to-many" relationship with DataSets

I have two tables, one containing patient information, the other, the notes for each patient.
(One patient, many notes for a patient).
Given this, in the Designer (which you access by right-clicking on the chosen DataSet), how do I create a one-to-many relationship? I have never performed this before.
Secondly, for the patient notes table, how would I add a note to a patient record using SQL syntax? Note, this is not updating an existing one, but adding a completely new one to the patientNotes table using the unique patient ID number as the reference (so only that specific patient has that note added to them, not them and everyone else).
Very technically speaking, you don't need to do anything to create a one-to-many relationship. You just have to have the two tables set up as you have them and use them as you intend on using them. I work in data warehousing and unfortunately a great many of our relationships like this are not formalized with any sort of key or constraint.
The correct way to do it is to implement a foreign key constraint on the patient ID column on the patientNotes table. A FK will only allow you to insert data into patientNotes IF the patient ID exists in the patient table. If you would try to insert a note into your table that has a patient ID that doesn't exist in the patient table, the insert would fail and the SQL engine would give you an error. Note that the column on the patients table that you are creating the FK to must be a primary key.
Inserting data will really go as any other insert would:
INSERT INTO dbo.patientNotes (patientId, NoteText)
VALUES(4265, 'During his 8/14/2014 visit, Mr. Cottinsworth complained of chest pains. Evidently he has been wearing a lady''s corset to hide his large gut. Advised the very portly Mr. Cottinsworth to discontinue corset use'
You could toss that in a SP, put it in your code and use parameters for the patientId and NoteText, however you wanted to do it.
As far as doing this all in Visual Studio graphically, I can't be of much help there. I typically use the TSQL editor and type out what I want to do to the DB. I'm sure there are tutorials abound on how to set up FKs on Visual Studio.
Further reading:
http://msdn.microsoft.com/en-us/library/ms189049.aspx
http://www.scarydba.com/2010/11/22/do-foreign-key-constraints-help-performance/
what are the advantages of defining a foreign key

How to maintain referential integrity when parents tables keys are changed?

I have created a C# app that makes a clone copy from an MS Access database and migrates the data to another DB server, but that will require changing the primary keys. What is the best way to maintain the referential integrity to the child tables when the parent tables keys are changed?
Thanks,
Andrew
You may already know this but your primary key column values should not be changing, much, if at all. However, that aside, you don't mention what database you are using. But with SQL Server, you can set up FK's to do what is called a cascading update. This means that if a PK value changes, all FK rows in child tables will have the value changed as well.
The following is an article describing this: http://blogs.techrepublic.com.com/datacenter/?p=128
I'm assuming you have autoIncrement set as the datatype on the PK field of an Access table and you want equivalent functionality in your new db.
Import the Access tables into destination tables with numeric, not auto-increment, data types. Then add your RI back between parent and child tables. Then edit your PK field to auto increment.
I did end up using composite primary keys since each time the app makes a clone copy it is a "snapshot" of the entire dataset. I've therefore added a columne called "Revision" and set each table's primary key to Pk = OID + REVISION.
For the child table it should reference the parent table by their primary key, which means the foreign key will also be composite. How do you achieve that relationship in Access? What I have done is in Access 2007 go to "Database Tools" -> "Relationship" and there edit the relationship so that it displays the following:
(parent Oid) 1 <--- many (child parentKey), (parent Revision) 1 <--- many (child Revision)
Please tell me is this is the way to do it. Or if someone can tell me how to achieve that using SQL commands I'll try that too.
Thanks,

MVC Entity Model not showing my table

I have a database with multiple tables, and some basic relationships. Here is an example of the problem I am having:
My Database:
**Org**
ID
Name
etc
**Detail1**
ID
D1name
**Org_Detail1**
Org_ID
Detail1_ID
**Detail2**
ID
D2Name
**Org_Detail2**
Org_ID
Detial1_ID
BooleanField
My problem is, the Org_detail1 table is not showing up in the entity model, but the Org_Details2 table does.
I thought it may have been because the Org_Detail1 table only contains two ID fields that are both primary keys, while the Org_Details2 table contains 2 primary key ID fields as well as a boolean field.
If I add a dummy field to Org_detail1 and update it, it still won't show up and wont allow me to add a new entity relating to the Org_Detail1 table. The table won't even show up in the list, but it is listed under the tables.
Is there any solution to get this table to appear in my model?
Seems like I may just need to completely delete the model and recreate it. Adding dummy fields is the only solution I've found.
Not sure this is an MVC problem.
Does a Detail1 collection turn up in your Org entity and an Org collection show up in your Detail1 entity. This is the normal behaviour for Entity framework for a many to many intersecting table with no other tangible data.
If not then maybe the foreign key constraints are not defined.

Edit composite key value using LINQ

I have a table which uses three columns as a composite key.
One of these column values is used as a sequence tracker for ordered related records. When I insert a new record I have to increment the sequence numbers for the related records that come after the new record.
I can do this directly in SQL Server Management Studio, but when I attempt this in LINQ I get the following error:
Value of member 'Sequence' of an object of type 'TableName' changed.
A member defining the identity of the object cannot be changed.
Consider adding a new object with new identity and deleting the existing one instead.
Can anyone suggest a way around this limitation?
(Adding a new record (as suggested by the error message) isn't really an option as the table with the composite key has a relationship with another table.)
Changing primary keys is a "code smell" in my book.
The fix we implemented was as follows
Deleted the relationship that used the composite key
Added autoincrement ID field, set that as primary key
Added Unique contstraint to the three fields that we were previously using as our
Re-created the relationship using the three fields that were previously our primary key
I worked around this by using a SQL stored proc to update one of the primary keys and calling it from LINQ.
I think the compiler is right. The only way of doing this is creating a new record and deleting the old one.
(Adding a new record (as suggested by
the error message) isn't really an
option as the table with the composite
key has a relationship with another
table.)
I think there's no problem with this. Just copy all the fields of your entity, set the new sequence, and set also any relation by just assigning the old EntitySet reference to the new one. I tried this and it updates correctly.
Besides of this, couldn't you just create a new ID column with auto-increment? I agree with #ocdecio. I think changing primary keys is poor design ...
I don't know LINQ, but would this work if you have cascading update defined on the SQL Server for the FK relationships?
Mind, I think using a composite key is a bad idea and changing one is a worse idea. The primary key should not change. Too many things can get broken if the primary key changes. And what do you do when the primary key changes and it is now not unique? If you do this, you will need a way to handle that as well because it will happen.

Categories