如何使用LINQ to SQL将数据保存到关系表? [英] how to save data to relationship table with LINQ to SQL?
问题描述
假设我有三个表:Tab1(Cola ,,,,,)Tab2(Colb,....),tab3(可乐,colb,...)
Cola是tab1的主键,colb是tab2的主键。 Tab3是tab1和tab2的关系,所以cola,colb是tab3的外键。
对于tab1和tabl2,因为它们是实体,所以我可以使用datacontext db添加一个新的例如:
db.Tab1s.InsertOnSubmit(tab1 obj);
db.Save();
db.Tab2s.InsertOnSubmit(tab2 obj);
db.Save();
但是当我尝试以类似的方式向tab3插入数据时:
db.Tab3s.InsertOnSubmit(tab3 obj);
我收到异常错误说tabl3没有主键。 tab3只有cola上的索引,colb:
- ex {&'无法对'Table(Tab3)'执行创建,更新或删除操作,因为它没有主键。 "} System.Exception {System.InvalidOperationException}
如何解决此问题?
你需要按照它的建议去做,并在tab3上创建一个主键:
用于改变表格tab3添加约束PK_Tab3主键(可乐,colb)
你有什么理由* *不想*在tab3上使用PK?
乔
Suppose I have three tables: Tab1(Cola, ,,,,) Tab2(Colb,....), tab3(cola, colb,...)
Cola is primary key for tab1, colb is primary key for tab2. Tab3 is a relationship of tab1 and tab2, so cola, colb is foreign keys for tab3.
For tab1 and tabl2, because they are entity, so I can use datacontext db to add a new instance like:
db.Tab1s.InsertOnSubmit( tab1 obj);
db.Save();
db.Tab2s.InsertOnSubmit(tab2 obj);
db.Save();
But When I try to insert data to tab3 in similar way:
db.Tab3s.InsertOnSubmit(tab3 obj);
I got exception error said that tabl3 has no primary key. tab3 only have a index on cola, colb:
- ex {"Can't perform Create, Update or Delete operations on 'Table(Tab3)' because it has no primary key."} System.Exception {System.InvalidOperationException}
How to resolve this issue?
You need to do as it suggests and create a primary key on tab3:
alter table tab3 add constraint PK_Tab3 primary key (cola, colb)
Is there any reason you *wouldn't* want a PK on tab3?
Joe
这篇关于如何使用LINQ to SQL将数据保存到关系表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!