Search code examples
c#.netlinqlinq-to-sqldatacontext

DataContext always ReadOnly, even though a primary key exists


I'm attempting to update a value in my Database, but the IsReadOnly property is always coming back as True. According to Microsoft, that property

Gets a value that indicates whether the type of the entities contained in this Table instance has a primary key

The problem is, my DB DOES have a PK set.

DB definition:

CREATE TABLE TestTable 
(
    ID int NOT NULL PRIMARY KEY,
    Value varchar(50) NOT NULL
); 

INSERT INTO TestTable (ID, Value) 
VALUES (1, '6caaef02-fc34-4112-9574-4c5923c5624d');

LINQ object definition:

[Table( Name = "TestTable" )]
public class TestTable
{
    [Column] public int ID { get; set; }
    [Column] public string Value { get; set; }
}

The modification code:

DataContext db = new DataContext(ConnStr);  // Just a standard SQL Server connection string
var b = db.GetTable<TestTable>().IsReadOnly;   // Always 'True'
var firstResult = db.GetTable<TestTable>().FirstOrDefault();
Console.WriteLine( firstResult.ID + " " + firstResult.Value );  // The current DB value logs here correctly

firstResult.Value = Guid.NewGuid().ToString();
db.GetTable<TestTable>().Single(c => c.ID == 1).Value = Guid.NewGuid().ToString();

var x = db.GetChangeSet();   // Always {{Inserts: 0, Deletes: 0, Updates: 0}}
db.SubmitChanges(ConflictMode.FailOnFirstConflict);

No exceptions are thrown, it just doesn't do anything either.

Can anyone tell me what I'm missing here?


Solution

  • ColumnAttribute has property IsPrimaryKey in which indicates PrimaryKey. LINQ to SQL do not check database for PK while running queries. Mapping should be set by attributes.

    [Table( Name = "TestTable" )]
    public class TestTable
    {
        [Column(IsPrimaryKey = true)] public int ID { get; set; }
        [Column] public string Value { get; set; }
    }