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.