Question

I have a couple of tables like so, in SQL server

Table1

Id (pk), Name

Table2

Table1_Id (fk), Title, Description, SomeData

When inserting from code (using C#) i want to avoid having to make two requests to create this data.

Is there an ORM, or something like Simple.Data which will handle it if I call

var myObject = new MyObject()
{
    Name = "Name",
    Description = "Description",
    Title = "Title",
    SomeData = "SomeData"
};
db.Table1.Insert(myObject);

I guess there may be something out there that is clever enough to recognize the foreign keys in use here?

The main difficulty here I guess is that my Ids are being auto-incremented by SQL, so mapping the foreign key could be tricky.

Thanks!

Was it helpful?

Solution

You can use entity framework to do it.

Basically you define an Entity then you map it to more than a SQL table.

I.e. you can define an abstract entity Person and concrete entities Employes and Managers and make them inherit Person.

Then in the mapping you map shared properties to the Person SQL table and specific properties on the Employees and Managers SQL tables.

There are several tutorials online on how to do it using. i.e.

The resulting code is similar to what you posted:

using (var db = new TestContext()){
  db.Managers.Add(new Manager { Name = "a", ... });
  db.SaveChanges();
}

OTHER TIPS

This is very easy with NHibernate.

Use a join (example with XML, it's also possible to map by code):

<class name="MyObject" table="Table1">
  <id .../>
  <property name="Name" />

  <join table="table2">
    <key column="Table1_Id" />
    <property name="Description" />
    <property name="Title" />
    <property name="SomeData" />
  </join>
</class>

It is fully transparent to the C# code. There is no need to change your entities (e.g. use a base class or something).

var myObject = new MyObject()
{
    Name = "Name",
    Description = "Description",
    Title = "Title",
    SomeData = "SomeData"
};
session.Save(myObject);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top