inserting extra data in linq to sql partial class - linq-to-sql

I have a L2S generated class called Accounts, I have a L2S class called UsersInAccounts I need to add a function call AddUserToAccount(accountid, userid) should/could this function be added to the partial Accounts class I have created or are partial classes used for getting data rather than editing data
public partial class Account
{
public void addUser(Guid userid)
{
// code
}
}

I don't think that what you are doing is a problem. In your code, you'd probably have an Account instance that you want to do things with so being able to do this:
Account theAccountIWant = GetTheAccount();
theAccountIWant.addUser(myUsersGUID);
...seems pretty intuitive. It might be an idea to do some error trapping inside your addUser method and pass back some sort of success status but that's another discussion.
edit: As advised, if you then retrieve a User object and want to attach it to the Account using the AccountUsers property then this is no use unless you pass the DataContext in.

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.

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 to SQL table naming

I am using VS2010 and C#
When I map/select my database tables with LINQ to SQL I have to option to change the "member" propery, but when i delete the table (because I changed something in the schema for example) and add it again the member value gets "reset". Is it possible to set/override this member programmaticly, so that I dont have to change it by hand everytime
I mean the member option of
'<'Table Name="dbo.table1" Member="table1">
All L2S ORM classes are partial, so you should be able to encapsulate the table in another property by extending the DataContext class e.g.
public partial class MyDataContext
{
public IEnumerable<Entity> Table
{
get { return DatabaseTable; }
}
}
So in the above scenario you would make your DatabaseTable private and expose it through a another property. You may still need to change that particular piece of code manually if you change the name of your table, but it means you are only changing it once and don't have to change it everytime you reference the table somewhere in your code.

Linq to SQL Extensibility Method Definitions

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);