LINQ to SQL -- Same User Object, different data context - linq-to-sql

I have a user object called UserSystem, which is created by a static factory class that returns User Systems. Because the factory class only exists to create this object once, then disposes, is it possible to associate my persisted UserSystem object with another instance of my database context that I create at a later point?
I would like to avoid having to query my new DatabaseContext to find the matching UserSystem object and simply associate the persisted user object from the first DatabaseContext class with my new DatabaseContext.
Thanks!
George

You probably want to Attach your object to the DataContext. There are many articles about this, for example this one. Be careful though - this method is not intended to allow you to attach objects that are already attached to another DataContext, it is only for deserialized objects that are completely unattached, which I assume is what you have.

You may use the Attach method on the Table<T> object to insert a detached data object into it. You may insert it in a modified state, or in an unmodified state. If you insert it in a modified state, the next SubmitChanges() call will include it.
The Table(Of TEntity) Attach method overloads

Related

save values from 2 classes in grails

I have 2 classes named User.groovy and Employee.groovy and I used MYSQL to save the data. What I want is to create a new User account and save it to the User table and also save some of the data to Employee table. How can I do this? I've tried extending the user to Employee but the data only saved to User and not to Employee. But If I don't extend the User, the data is only saved to Employee. What should I do so that the data simultaneously saves to two database tables at the same time? Please help me.
Actually have this in my class user:
class User {
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
.....}
and employee:
class Employee {
String name
String email
String jobDesc
....}
So what should I do next? I'm sorry for this, I'm still starting to learn grails.
Grails paradigm (as far as scaffolding is concerned) is one form - one object. As long as you stick to this paradigm, you get all the goodies, such as input validation and error reporting for free (you may also consider using the Fields plugin here http://grails.org/plugin/fields).
However, sometimes you need to collect info and create two or more objects through single form. Usually this happens when you need to initiate new subscription and collect info for both subscription details (say, Subscription entity) and user info (User entity). This is where command objects come to rescue.
http://grails.org/doc/latest/guide/theWebLayer.html#commandObjects
So, instead of expanding/bending SubscriptionController or UserController (or UserController and EmployeeController, as per your example), you create SignUpController, which handles SignUpCommand object. The SignUpCommand object is not intended to be saved, it is used as a backing object for the SignUpController.create form. When it validates, you use the signUpCommand object data to initialize 2 domain objects (that is Subscription and User) and save these objects individually within the same transaction.
You can either delegate the save operation to a service say,
if (signUpCmd.validate()) {
SignUpService.save(signUpCmd))
}
or create and save both objects right on the spot within controller
if (signUpCmd.validate()) {
Subscription subscription = new Subscription(plan: signUpCmd.plan, ...)
subscription.save()
User user = new User(username: signUpCmd.username, ...)
user.save()
}
it is mostly matter of taste and style.
Instead of calling save() directly to your user instance, call a service class that saves both the user and the employee in one atomic operation. Like, for instance:
class UserController {
/*Injection of your service in the controller class*/
def userService
And then in the save action in this same controller:
userService.save(user) // userService.save(params)
And inside this service method you will extract the data (user or params, whatever floats your boat) you want to save in a different table as long as the usual user object.

JDBC update of different fields

I'm developing Web Service that has access to database via JDBC. I'm using DAO pattern. I've implemented all necessary methods: findAll, add, update, delete. But I got confused with update method. It has Object as input parameter. But how does he know which field needs to be updated. For example, I need to update field 'name' I use query 'update table set name='smth where id=2' but if I need to update 'surname'?? what is the best practice to tell update method what actually to update?
thank you
You'll need to change your method signature to include a Map of column names and values.
public interface FooDao<K, V> {
// other methods here, of course.
public void update(V target, Map<String, Object> parameters);
}
Have a look at the Spring JDBC template for a nice example of how to design and implement such a thing.

Accessing non-related entities in LinqToSql entity classes

In LinqToSql, if I want to access a non-related entity in an entity partial class, how do I do this without creating a new DataContext?
Here's the scenario:
I have the tables Client, IssueType and ClientIssueType. A Client may specify a list of IssueTypes if they do not want to use the default IssueTypes. I have the default IssueTypes in the ClientIssueType table with a ClientId of null.
In my Client partial I'd like to try to retrieve all IssueTypes, and if none are found, return all default IssueTypes. The only way I can see of accessing the IssueTypes with a null ClientId is by accessing the table through a new DataContext, which is problematic once I want to start assigning them to Issues.
Where am I going wrong?
I have resolved the issue by moving the logic out of the entity partial class and into the DataContext partial class. When I call the method I pass in the Client entity.

Forcing LINQ to use a Stored Procedure when accessing a Database

I've done some searches (over the web and SO) but so far have been unable to find something that directly answer this:
Is there anyway to force L2S to use a Stored Procedure when acessing a Database?
This is different from simply using SPROC's with L2S: The thing is, I'm relying on LINQ to lazy load elements by accessing then through the generated "Child Property". If I use a SPROC to retrieve the elements of one table, map then to an entity in LINQ, and then access a child property, I believe that LINQ will retrieve the register from the DB using dynamic sql, which goes against my purpose.
UPDATE:
Sorry if the text above isn't clear. What I really want is something that is like the "Default Methods" for Update, Insert and Delete, however, to Select. I want every access to be done through a SPROC, but I want to use Child Property.
Just so you don't think I'm crazy, the thing is that my DAL is build using child properties and I was accessing the database through L2S using dynamic SQL, but last week the client has told me that all database access must be done through SPROCS.
i don't believe that there is a switch or setting that out of the box and automagically would map to using t sprocs the way you are describing. But there is now reason why you couldn't alter the generated DBML file to do what you want. If I had two related tables, a Catalog table and CatalogItem tables, the Linq2SQL generator will naturally give me a property of CatalogItems on Catalog, code like:
private EntitySet<shelf_myndr_Previews_CatalogItem> _shelf_myndr_Previews_CatalogItems;
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="CatalogItem", Storage="_CatalogItems", ThisKey="Id", OtherKey="CatalogId")]
public EntitySet<CatalogItem> CatalogItems
{
get
{
return this._CatalogItems;
//replace this line with a sproc call that ultimately
//returns the expected type
}
set
{
this._CatalogItems.Assign(value);
//replace this line with a sproc call that ultimately
//does a save operation
}
}
There is nothing stopping you from changing that code to be sproc calls there. It'd be some effort for larger applications and I'd be sure that you be getting the benefit from it that you think you would.
How about loading the child entities using the partial OnLoaded() method in the parent entity? That would allow you to avoid messing with generated code. Of course it would no longer be a lazy load, but it's a simple way to do it.
For example:
public partial class Supplier
{
public List<Product> Products { get; set; }
partial void OnLoaded()
{
// GetProductsBySupplierId is the SP dragged into your dbml designer
Products = dataContext.GetProductsBySupplierId(this.Id).ToList();
}
}
Call your stored procedure this way:
Where GetProductsByCategoryName is the name of your stored procedure.
http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx

Linq SubmittingChanges after assigning new object

If I make changes to an existing linq object by assigning a "new" object of the same type (with different values), SubmitChanges does not make the changes in the database. why not?
existing= new Data.Item{a=1, b=2...};
vs
existing.a= 1;
existing.b= 2;
Because you are not changing the object, you are assigning a new object to the variable.
You need to assign to fields one by one, (or InsertOnSubmit... but that will create a new object in the database and it does not sound like that is what you want to do).
This approach will sort of work if you we assigning the newly created object to a field of an object that LINQ to SQL knows about, but once again, that would be creating a new object rather than changing the one that field previously pointed to (which could result in a bunch of garbage rows in your database if you never get rid of them).