Why this approach don’t seem to work? What should be the standard approach?
[Database(Name = "Test")]
[Table(Name = "Order")]
public class Order
{
[Column(Name = "ID", IsPrimaryKey = true)]
public int ID { get; set; }
[Column(Name = "OrderDate")]
public DateTime OrderDate { get; set; }
public static Order Get(int id)
{
Order item = null;
try
{
DataContext dc = new DataContext(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True");
var items = from order
in dc.GetTable<Order>()
where order.ID == id
select order;
item = items.FirstOrDefault<Order>();
dc.Dispose();
}
catch (Exception ex)
{
item = null;
throw ex;
}
return item;
}
public bool Delete()
{
bool success = false;
try
{
DataContext dc = new DataContext(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True");
dc.GetTable<Order>().DeleteOnSubmit(this);
success = true;
}
catch (Exception ex)
{
success = false;
throw ex;
}
return success;
}
}
class Program
{
static void Main(string[] args)
{
Order order = Order.Get(1);
order.Delete();
Console.ReadLine();
}
}
This code generates the following exception:
InvalidOperationException : "Cannot remove an entity that has not been attached."
I have also tried the following:
DataContext dc = new DataContext(@"Data Source=(local)\sqlexpress;Initial Catalog=Relationships_Test;user=;password=;Integrated Security=True");
dc.GetTable<Order>().Attach(this);
dc.GetTable<Order>().DeleteOnSubmit(this);
It didn’t work either.
If you have an object (Order item in this case) that is created in the context of a DataContext, once you Dispose the DataContext, that object is orphaned.
To delete an orphaned object from the database, you need to either not dispose the original DataContext or somehow attach the object to a new DataContext (which can be tricky).
The easiest way to deal with this is to new the DataContext in your Main method and then Dispose the DataContext at the end of the main method (that is a standard pattern).