linq Can't perform Create, Update, or Delete o

2020-08-18 05:22发布

how i can add the rows in table when the table not have primary key.

标签: c# linq
7条回答
淡お忘
2楼-- · 2020-08-18 05:56

Let me illustrate with a sample:

SampleDataContextDataContext db = new SampleDataContextDataContext();
Employee emp = new Employee() {
      FirstName = "Experts",
      Lastname = "Comment",
      Address = "rs.emenu@gmail.com"
};

db.Employees.InsertOnSubmit(emp);
db.SubmitChanges(); 

The above code was giving the same error when trying to insert a new row. The reason behind this issue is that LINQ does not provide the facility to insert data into a table without a primary key. At this point you have two options which you can use to perform the insert operation.

1.Create a store procedure and call it from LINQ.

SampleDataContextDataContext db = new SampleDataContextDataContext();
db.InsertEmployeeData("Experts","Comment", "rs.emenu@gmail.com");

Here I have created a stored procedure with the name InsertEmployeeData, and called it from the code. Simple and straight forward.

2.Create an insert statement and execute using LINQ.

SampleDataContextDataContext db = new SampleDataContextDataContext();

string insertStatement = "Insert into Employee values('Experts', 'Comment','rs.emenu@gmail.com')";
db.ExecuteQuery<Employee>(insertStatement);

Here I created a normal insert query and executed using the the LINQ ExecuteQuery method.

查看更多
Ridiculous、
3楼-- · 2020-08-18 06:08

Some tables (like Vendor provided tables) DO NOT HAVE A PRIMARY KEY!

Every answer says "add a primary key".

Look, I wouldn't be asking if I could just add one. The conditions are preset not by me.

Is there a way to JUST WRITE. No reading, deleting or updating is required.

查看更多
Ridiculous、
4楼-- · 2020-08-18 06:14

If you can't set it in the db, set the primary key in the linq2sql designer.

If there is no subset of columns that can be used as primary key, mark them all as part of the primary key.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-08-18 06:15

I may be wrong here, since I have no way to verify right now, but I believe you can tell Linq to Sql that a field is a primary key, even if it's not actually one in the database. This assumes that the data in the field is in fact unique and can be used as a key even if it's not defined as one.

If the table has no primary key, but contains unique data that can be used as a key, then tell L2S in the dbml that this is the primary key.

If the table does not contain unique data that can be used as a key, then you have to write a sproc that deletes the data you want to delete.

查看更多
淡お忘
6楼-- · 2020-08-18 06:20

As your question's title says, LINQ to SQL can not perform create, update or delete operations on a table without a primary key. It's not possible.

So, you'll need to perhaps use DataContext.ExecuteCommand() to do those things, or better yet, refactor your database so the tables have primary keys.

查看更多
登录 后发表回答