简体   繁体   English

使用LINQ to SQL更新外键相关记录

[英]Updating Foreign Key dependent record using LINQ to SQL

I am working on application with more than 50 tables with a large amount of data. 我正在处理包含大量数据的50多个表的应用程序。

Let's say I have two tables: 假设我有两个表:

Parent { pID int (PK), pName varchar(30) }

and

Child { pID int (FK), cName varchar(30) }

Here is my query: 这是我的查询:

using(MyDBContext ctx = new MyDBContext())
{
    Child ch = ctx.Childs.Where( c => c.pID == 1).FirstOrDefault();
    ch.cName = "ABCDEF";
    ctx.SubmitChanges();   //  <--- Executes but nothing changes...
}

I have tried multiple existing values but ctx.SubmitChanges() doesn't work when updating child record. 我尝试了多个现有值,但更新子记录时ctx.SubmitChanges()不起作用。 Any workaround? 任何解决方法?

The table could not be updated, because it doesn't have primary key. 该表没有主键,因此无法更新。 SubmitChanges will not work if you dont have primary key on your table(child). 如果您的表(子级)上没有主键,则SubmitChanges将不起作用。 Set primary key on Child table like this 像这样在子表上设置主键

Child { ID int (PK), pID int (FK), cName varchar(30) }

and may everething will by ok 也许一切都会好的

I have found a solution by myself. 我自己找到了解决方案。 I have created an SQL Procedure which updates the record. 我创建了一个SQL过程来更新记录。 Here is, how I did it: 这是我的做法:

create procedure UpdateChildName
(
    @pID int,
    @name varchar(30)
)
AS
BEGIN
    update Child set cName = @name where pID = @pID;
END;

Linq to SQL Part: Linq to SQL部分:

using(MyDBContext ctx = new MyDBContext())
{
    ctx.UpdateChildName(1, "ABCDE");
    ctx.SubmitChanges();         //   <--- Now working great.
};

Now, I don't have any issue with FK or PK dependency... :) 现在,我对FK或PK的依赖没有任何问题... :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM