none
Cascade delete and Linq cache problem RRS feed

  • Question

  • For example, I have following classes.

     

    class A

    {

    public int ID { get; set; }

    }

     

    class B

    {

    public int AID { get; set; }  // this is the ID field of table A

    public int CID { get; set; }  // this is the ID field of table C

    }

     

    class C

    {

    public int ID { get; set; }  // this is the ID field of table C

    public list<B> Bs { get;  set; }

    }

     

    In database, I already created a relationship that when A is deleted, B will be automatically deleted for B.AID == A.ID. In my test database, following records exist,

     

    Table A has one record, ID = 1

    Table B has one record, AID = 1, CID = 2

    Table C has one record ID = 2

     

    In my test application, if I read an instance C, which also load list Bs that contains one record. Then using code to delete the record A for A.ID == 1, in database the record B.AID == 1 will be removed as well. However, if I use Linq to read the C instance with the condition C.ID==2, the original instance will be returned, i.e., list C.Bs still contain one element. But in database, table B now is empty.

     

    It seems that Linq internally keep the cache for all the instances it readed. I don't know how long the life time could be. But there seems no way to remove it from cache. The only way I found is to create a fresh DataContext. Can anybody suggest a better way getting around this problem. I am sure this is a Linq bug.

     

    Thank

     

    Chris

    Tuesday, April 1, 2008 10:34 AM

Answers

  • There is a DeleteRule property on the Association attribute. The designer does not set it, but SqlMetal.exe does.  It also may not do what you think it might.  LINQ to SQL only sees that property as information to use if you call CreateDatabase.  LINQ to SQL does not simulate cascade delete behaviors, it relies on the database to do that. 

     

    Monday, May 12, 2008 8:46 PM

All replies

  • Nobody had this problem? Or it is just me?

     

    Thursday, April 3, 2008 11:27 AM
  • There is a DeleteRule property on the Association attribute. The designer does not set it, but SqlMetal.exe does.  It also may not do what you think it might.  LINQ to SQL only sees that property as information to use if you call CreateDatabase.  LINQ to SQL does not simulate cascade delete behaviors, it relies on the database to do that. 

     

    Monday, May 12, 2008 8:46 PM
  • The method DataContext.Refresh() can be used to retrieve the newest data from DB for retrieved entities.

    Thursday, June 5, 2008 4:20 PM