Reputation: 121
I'm using a Data Access Layer based on PetaPoco (DotNetNuke 7.0). I've used it successfully when working with relatively simple objects but I now have to insert an object which contains at least one property which is a List of other objects.
For example:
class Person
{
public Person(){}
public string name { get; set; }
public List<Address> addresses { get; set; }
}
class Address
{
...
}
The actual object I'm working with is much more complex than the example above - there are at least four composite List objects in the object to be inserted into the repository.
What I'd like to be able to do is define the table in SQL and to be able to make a simple call to PetaPoco like this:
public static void AddOrder(Person person)
{
using (IDataContext context = DataContext.Instance())
{
var repository = context.GetRepository<Person>();
repository.Insert(person);
}
}
The background to this is that the object is passed in to a web service from a Knockout/jQuery front-end so a JSON string is converted to a data object which must then be stored on the database.
I think there are three questions really:
How do I write the SQL table which represents Person and the contained Addresses List?
How do I write the necessary PetaPoco code to insert the Person object together with any objects it contains?
Should I forget about trying to store the object on the database and just store the JSON string on the database instead?
Thanks for looking :)
Upvotes: 3
Views: 1366
Reputation: 582
I haven't installed DotNetNuke 7 yet, however I examined the source code at codeplex and I think you can do it this way:
public static void AddOrder(Person person)
{
using (IDataContext context = DataContext.Instance())
{
var repositoryPerson = context.GetRepository<Person>();
var repositoryAddrress = context.GetRepository<Address>();
context.BeginTransaction();
try
{
repositoryPerson.Insert(person);
foreach(var address in person.addresses)
{
repositoryAddress.Insert(address);
}
context.Commit();
}
catch (Exception)
{
context.RollbackTransaction();
throw;
}
}
}
I haven't tested it so I can't guarantee it works, however this seems right to me.
Upvotes: 1