Given that you have 2 table in many to many relationship, how create using Linq?
First of all you need to normalize it to 1 to many format. Since you are using Linq, it is safer that each and every table has 1 identity autonumbered column to prevent any CRUD failures (Hope this will be fixed soon).
Now you got 3 tables, since you are dealing with > 1 table therefore you're recommended to create a transaction to perform any CRUD.
Here are the code snippet
using (System.Transactions.TransactionScope scope = new
System.Transactions.TransactionScope())
{
try
{
//initialize it and
the connection created
pfData = new PersonalFinanceDataContext();
//Create spending type, the first table
SpendingType
spendingType = new SpendingType();
spendingType.Name = accountName;
//Create Account, the second table
Account accPayable = new
Account();
accPayable.AccountName = accountName;
//Map them together, by a mapper table
SpendingAccount
spendingAccount = new SpendingAccount();
spendingAccount.Account =
accPayable;
spendingAccount.SpendingType = spendingType;
//remember to add into database context else everything will be
lost!
pfData.SpendingAccounts.Add(spendingAccount);
//Save it
pfData.SubmitChanges();
//commit it, everything is successfully done!
scope.Complete();
}
catch(Exception ex)
{
throw "Bad linq" + ex;
}
}
hope you have some basic idea of how easy that linq to sql could do for you.
No comments:
Post a Comment