0

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?

2
  • [Column(IsPrimaryKey = true)] public int ID { get; set; }? Commented Dec 4, 2023 at 18:24
  • @Svyatoslav Danyliv That works! Please turn it into an answer. Commented Dec 4, 2023 at 18:47

2 Answers 2

1

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; } } 
Sign up to request clarification or add additional context in comments.

Comments

-1

looks like you're used db-first approach, and you model your entity manually.

  1. if you want stay with manual modeling, try with setting [Key] attribute for ID property, that will indicate it's PK. - https://www.entityframeworktutorial.net/code-first/key-dataannotations-attribute-in-code-first.aspx
  2. Second way - try to generate model/s automatically with tool - https://www.entityframeworktutorial.net/entityframework6/create-entity-data-model.aspx

1 Comment

This question is not related to EF. Before EF, LINQ To SQL was a first LINQ provider which worked only with SQL Server.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.