Being new to Linq-to-SQL, I ran into one of it's Gotchas today and I wanted to share my solution and then ask if there was something better.
I'm setting up a staff allocation tool for my work. There are three basic class/tables: Employee, Project, Assignment. Importantly here, Assignment serves as a junction table between Employee and Project. I ran into my problem on a form that contained a DataGridView that was bound to a BindingList. The problem came when a user decided to create a new assignment, but then before saving their changes they decided to delete the new assignment that they had just created. Unfortunately, saving caused the deleted assignment to be saved anyhow!
Here is a (somewhat simplified) version of my naive delete handler:
//Assume that assignments is the BindingList<Assignment> bound
//to the dataGridView
private void DeletedRowHandler(object sender, EventArgs e)
{
DataGridViewRow row = dataGridView.GetSelectedRow();
Assignment assignment = (Assignment) row.DataBoundItem();
assignments.Remove(assignment);
try
{
db.Intervals.DeleteOnSubmit(assignment);
}
catch
{
}
}
After much weeping and gnashing of teeth, it occurred to me that through the magic if Linq-to-SQL, the Employee and Project which the deleted assignment had been associated with already had a reference to the Assignment that I thought I was deleting. This was causing it to be submitted to the database eventually.
The fix that I ended up using was to insert the following code in my delete handler:
assignment.Employee = null;
assignment.Project = null;
This appears to work.
My question: Is this what you're supposed to do? Or is there a cleaner approach that I don't know about?
Note: In writing this question I got a friendly, automated notice that this question was likely going to be closed. If you decide to close it, then please be kind enough to tell me why and to point me in a good direction.
Suggest deleting by ID, if you can. Let the DataContext find the entity by its key, and supply that entity to the Delete method.
DeleteAssignment(someRowID);
...
public void DeleteAssignment(int assignmentID)
{
db.Assignments.DeleteOnSubmit(
db.Assignments.SingleOrDefault(a=>a.ID==assignmentID)
);
db.SubmitChanges();
}
Related
I have this pretty simple method:
internal void Add(RecipeRecord recipeRecord)
{
this.Database.GetTable<RecipeRecord>().InsertOnSubmit(recipeRecord);
this.Database.SubmitChanges();
}
The entity I'm inserting is a valid entity. When I call SubmitChanges, nothing happens. No errors and no row added to the database. There is no transaction active. If I call GetChangeSet() on the context object, I see the single entity to add. After SubmitChanges(), the change set is empty.
Can anyone see what might be wrong?
I think you may have to use context.attach I ran in to a similar issue and that got me going in the right direction.
I have a standard update happening via linq to sql but the data does not persist to the database.
I am using an auto-generated class via the .dbml file designer.
The update statement is below:
public static void UpdateEmailsInWorkingTable(Guid emailGuid, string modifiedEmail)
{
using (EmailDBDataContext DBContext = new EmailDBDataContext())
{
EmailAddress_Update EAUpdated = (from e in DBContext.EmailAddress_Updates
where e.EmailGuid == emailGuid
select e).SingleOrDefault();
EAUpdated.EmailAddress = modifiedEmail;
EAUpdated.IsValid = 'Y';
EAUpdated.UpdateFlag = true;
EAUpdated.LastChangedDtTm = DateTime.Now;
try
{
DBContext.SubmitChanges(ConflictMode.FailOnFirstConflict);
}
catch (ChangeConflictException ex)
{
// do stuff here
}
}
}
I looked through my auto-generated DataContext class and the only glaring difference is that the table in question EmailAddress_Update does not implement the two interfaces INotifyPropertyChanging and INotifyPropertyChanged that the other auto-generated entities do.
I am assuming that this is the cause of why the changes are not being persisted is it not???
To put it simply none of the Extensibility Method Definitions get generated for any part of this one class. If this is the cause of my problems, what in the database would be causing this to not auto-generate properly??
Thanks~
I posted this question on MSDN as well here: MSDN Linq to Sql if you wanted to see the replies. But I found part of the reason why the code doesn't generate.
Here is a piece from my MSDN response:
I created a small test table without a primary key and added it to the designer and sure enough it didn't generate any of the Extensibility methods for that instance.
So I then added a primary key to the same table and re-added it to the designer and sure enough all of the extensibility methods and change tracking events were generated.
My question now is why must there be a primary key for this stuff to auto-generate?
Ok so to answer my own question "My question now is why must there be a primary key for this stuff to auto-generate?" I found it in the book Pro LINQ written by Joe Joseph C. Rattz, Jr.
I was reading how to handle views versus tables and he says this:
"Because the entity classes generated for views do not contain entity class properties that are mapped as primary keys, they are read-only. If you consider that without primary keys, the DataContext has no effective way to provide identity tracking, this makes sense."
Mystery and problem solved.
If I have a LINQ to SQL table that has a field called say Alias.
There is then a method stub called OnAliasChanging(string value);
What I want to do is to grab the value, check the database whether the value already exists and then set the value to the already entered value.
So I may be changing my alias from "griegs" to "slappy" and if slappy exists then I want to revert to the already existing value of "griegs".
So I have;
partial void OnaliasChanging(string value)
{
string prevValue = this.alias;
this.Changed = true;
}
When I check the value of prevValue it's always null.
How can I get the current value of a field?
Update
If I implement something like;
partial void OnaliasChanging(string value)
{
if (this.alias != null)
this.alias = "TEST VALUE";
}
it goes into an infinte loop which is unhealthy.
If I include a check to see whether alias already == "TEST VALUE" the infinate loop still remains as the value is always the original value.
Is there a way to do this?
The code snippets you've posted don't lend themselves to any plausible explanation of why you'd end up with an infinite loop. I'm thinking that this.alias might be a property, as opposed to a field as the character casing would imply, but would need to see more. If it is a property, then you are invoking the OnAliasChanging method before the property is ever set; therefore, trying to set it again in the same method will always cause an infinite loop. Normally the way to design this scenario is to either implement a Cancel property in your OnXyzChanging EventArgs derivative, or save the old value in the OnXyzChanging method and subsequently perform the check/rollback in the OnXyzChanged method if you can't use the first (better) option.
Fundamentally, though, what you're trying to do is not very good design in general and goes against the principles of Linq to SQL specifically. A Linq to SQL entity is supposed to be a POCO with no awareness of sibling entities or the underlying database at all. To perform a dupe-check on every property change not only requires access to the DataContext or SqlConnection, but also causes what could technically be called a side-effect (opening up a new database connection and/or silently discarding the property change). This kind of design just screams for mysterious crashes down the road.
In fact, your particular scenario is one of the main reasons why the DataContext class was made extensible in the first place. This type of operation belongs in there. Let's say that the entity here is called User with table Users.
partial class MyDataContext
{
public bool ChangeAlias(Guid userID, string newAlias)
{
User userToChange = Users.FirstOrDefault(u => u.ID == userID);
if ((userToChange == null) || Users.Any(u => u.Alias == newAlias))
{
return false;
}
userToChange.Alias = newAlias;
// Optional - remove if consumer will make additional changes
SubmitChanges();
return true;
}
}
This encapsulates the operation you want to perform, but doesn't prevent consumers from changing the Alias property directly. If you can live with this, I would stop right there - you should still have a UNIQUE constraint in your database itself, so this method can simply be documented and used as a safe way to attempt a name-change without risking a constraint violation later on (although there is always some risk - you can still have a race condition unless you put this all into a transaction or stored procedure).
If you absolutely must limit access to the underlying property, one way to do this is to hide the original property and make a read-only wrapper. In the Linq designer, click on the Alias property, and on the property sheet, change the Access to Internal and the Name to AliasInternal (but don't touch the Source!). Finally, create a partial class for the entity (I would do this in the same file as the MyDataContext partial class) and write a read-only wrapper for the property:
partial class User
{
public string Alias
{
get { return AliasInternal; }
}
}
You'll also have to update the Alias references in our ChangeAlias method to AliasInternal.
Be aware that this may break queries that try to filter/group on the new Alias wrapper (I believe Linq will complain that it can't find a SQL mapping). The property itself will work fine as an accessor, but if you need to perform lookups on the Alias then you will likely need another GetUserByAlias helper method in MyDataContext, one which can perform the "real" query on AliasInternal.
Things start to get a little dicey when you decide you want to mess with the data-access logic of Linq in addition to the domain logic, which is why I recommend above that you just leave the Alias property alone and document its usage appropriately. Linq is designed around optimistic concurrency; typically when you need to enforce a UNIQUE constraint in your application, you wait until the changes are actually saved and then handle the constraint violation if it happens. If you want to do it immediately your task becomes harder, which is the reason for this verbosity and general kludginess.
One more time - I'm recommending against the additional step of creating the read-only wrapper; I've put up some code anyway in case your spec requires it for some reason.
Is it getting hung up because OnaliasChanging is firing during initialization, so your backing field (alias) never gets initialized so it is always null?
Without more context, that's what it sounds like to me.
If I have a Linq table of say User and I then do something like this;
public partial class DataAccessDataContext
{
partial void UpdateUser(User instance)
{
//do something here
}
}
What ends up happening is that the record is never updated in the database.
As soon as I get rid of the UpdateUser method the database is again updated.
I found something on the web that mentions that as soon as you implement any of the three extensibility methods of Insert, Update and Delete, then the database is no longer updated.
Is this correct and is there a way I can get this to work?
You need to call the Dynamic update method like;
this.ExecuteDynamicUpdate(instance);
I having a weird problem with Entity Framework with MySql database.
Here's the code that I've got.
public class testbase
{
private testEntities db = new testEntities();
public IQueryable<post> GetRecords()
{
return db.record;
}
}
Here record is a table in my database and this could should return all the rows in the table. I have only one row in there and when I do a db.record.Count(), I get 1.
But when I try to retrieve the rows themselves I get 'Function Evaluation timed out'.
What's happening? Anybody got any ideas?
Okay, this turned out to be a dud question. Ben M was right. Some googling revealed: -
EF does not behave well while debugging due to some issues in VS debugger. You get a 'Function evaluation timed out'.
Things work swell when you try the code without debugging.
I was testing as I go for my new EF+MySql+ASP.Net.MVC app, and since I am a n00b at all three I didn't realize that.
I haven't deleted the question yet because there for others like me. It's on the community to decide whether to let this question survive or go.
I pronounce this question officially a dud.