Common best practice for updating a record and its associated relationships in Linq-to-SQL

I have a very general question about updating an entry in Linq-to-SQL. Suppose in my data model I have a base record (Table - Person) with a ratio of m: m to a set of categories (Table - Category). Therefore, I have an associative table (PersonCategory) that has foreign keys for both PersonID and CategoryID.

When I want to update Person, I may have new PersonCategory entries to add, and you might want to delete other PersonCategory entries. What is the best practice for doing this? Do I want to delete all entries in Person.RelatedPersonCategories and then add new ones? Is LINQ-to-SQL smart enough to negotiate which entries in the PersonCategory table are actually added, edited, or deleted (based on the potential potential potential infection of it)?

Thanks for any help!

+3
source share
2 answers

DataContext , LINQ to SQL /update/delete rows , , , , DataContext.SubmitChanges().

:

using (var db = new DataContext())
{
    var person = db.Persons.Where(p => p.Name == "Foo").SingleOrDefault();

    if (person != null)
    {
        // Inserts a new row in the 'PersonCategory' table
        // associated to the current 'Person'
        // and to the 'Category' with name 'Employee'
        person.PersonCategories.Add(new PersonCategory() { CategoryName = "Employee" });

        // Updates the 'CategoryName' column in the first row
        // of the 'PersonCategory' table associated to the current 'Person'
        person.PersonCategories(0).CategoryName = "Consultant";

        db.SubmitChanges();
    }
}

, , DataContext, , .

/ , , , DataContext (TEntity).Attach, DataContext.SubmitChanges().

. , (TEntity).Attach .
MSDN:

, (, EntitySet ) . SubmitChanges, . , Attach .

:

// The 'Person' object has been detached
// from the originating 'DataContext', which is now disposed
person.PersonCategories.Add(new PersonCategory() { CategoryName = "Employee" });
person.PersonCategories(0).CategoryName = "Consultant";

using (var db = new DataContext())
{
    // Will detect added and deleted objects
    // in the 'PersonCategory' collection        
    db.Person.Attach(person);

    // Required to detect and modifications
    // to existing objects in the 'PersonCategory' collection
    foreach (var personCategory in person.PersonCategories)
    {
        db.PersonCategory.Attach(personCategory);
    }

    db.SubmitChanges();
}
+3

. PersonCategory - , , , InsertOnSubmit() DeleteOnSubmit(). PersonCategory .

, , , .

, - , , .

,

  • Person EntitySet<PersonCategory>

  • PersonCategory EntityRef<Person> EntityRef<Category>

  • Category EntitySet<PersonCategory>.

, , :

  • Person PersonCategory null, EntitySet<PersonCategory> , PersonCategory EntitySet<PersonCategory>

  • PersonCategory PersonCategory, Person Person.

, : LINQ to SQL , - .

0

Source: https://habr.com/ru/post/1718224/


All Articles