linq-to-sql.net-3.5crud

How do I update a SQL row given an ID with LINQ to SQL?


Given this schema:

Fruits
 - FruitID       INT PK
 - FruitName     NVARCHAR(30)
 - FruitStatusID INT NULL FK: Statuses

Statuses
 - StatusID      INT PK
 - StatusName    NVARCHAR(30)

If I have a FruitID in hand (just an int, not a Fruit object), how do I update the FruitName and null out FruitStatusID without loading the Fruit object from the database first?

Note: this solution gets me pretty far, but I can't figure out how to null out a FK column.

Answers in C# or VB, thanks!


Solution

  • This works but seems unnecessarily complicated:

    ''//initialize the values I'm going to null out to something
    Dim Tag As Data_Tag = New Data_Tag() With {
      .Data_Tag_ID = DataTagID, 
      .Last_Error_DateTime = New DateTime(), 
      .Last_Error_Message = "", 
      .Last_Error_Severity_Type_ID = -1 }
    
    ''//start change tracking
    DB.Data_Tags.Attach(Tag)
    
    ''//record changes to these properties (must be initialized above)
    Tag.Last_Error_DateTime = Nothing
    Tag.Last_Error_Message = Nothing
    Tag.Last_Error_Severity_Type_ID = Nothing
    
    DB.SubmitChanges()
    

    Surely there's a better way!

    (note: the weird comment syntax is solely for the code highliger--it doesn't like VB-style comments)