我在数据库中使用了两个表Complaint和ComplaintComments,但我只有一种表格可以提交数据。所以我怎样才能通过一种形式在多个表中提交记录(方法LINQ)。
答案 0 :(得分:0)
不确定您使用的是哪个ORM,但是可以尝试类似的操作。
{
/*CboComplaint.DataSource = db.ComplaintTypes.ToList();
CboComplaint.DataTextField = "ct_Name";
CboComplaint.DataValueField= "ct_Id";//"ct_Name";
CboComplaint.DataBind();
*/
//CboComplaint.SelectedIndex = + 2;
Complaint tc = new Complaint();
// ComplaintComment ta = new ComplaintComment();
var datetime = DateTime.Now;
tc.comp_Date_time = datetime;
var b = DropDownList1.SelectedIndex;
tc.comp_Type = Convert.ToInt32(b);
tc.comp_Details = txtCdetails.Text;
var c = cboCStatus.SelectedIndex;
tc.comp_Status = Convert.ToInt32(c);
tc.cust_Id = Global.cust_Id; // This is customer ID
tc.comp_Status = 1; // This is complaint Status
var d = cboCpriority.SelectedIndex;
tc.comp_Priority = Convert.ToInt32(d);
tc.comp_Location = txtloc.Text;
// ta.cc_Comments = txtComments.Text;
var dt = DateTime.Now;
// ta.cc_Timestamp = Convert.ToString(dt);
tc.comp_active = true;
ComplaintComment ta = new ComplaintComment();
ta.cc_Comments = txtComments.Text;
db.Complaints.ComplaintComments = ta;
db.Complaints.InsertOnSubmit(tc);
Response.Write("Your complaint has been submitted.<br/>");
db.SubmitChanges();
答案 1 :(得分:0)
为此,您需要定义一个DataContext来定义Linq To SQL实体中的表之间的关系,如下所述: Walkthrough: Querying across relatinonships
DataContext
看起来像这样:
public class ComplaintDataContext : DataContext
{
// Table<T> abstracts database details per table/data type.
public Table<Complaint> Complaints;
public Table<Comment> Comments;
public ComplaintDataContext(string connection) : base(connection) { }
}
在您的Complaint
实体中,您需要像这样定义与Comments
的关系:
private EntitySet<Comment> _Comments;
public Complaint()
{
this._Comments = new EntitySet<Comment>();
}
[Association(Storage = "_Comments", OtherKey = "{your fk name}")]
public EntitySet<Comment> Comments
{
get { return this._Comments; }
set { this._Comments.Assign(value); }
}
Linq to SQL将使用此信息来为您管理关系。您还需要启用对象跟踪:ObjectTrackingEnabled and linq-to-sql
您还应该阅读有关Object States and Change-Tracking的文档
答案 2 :(得分:0)
解决方案:
创建aspx文件: 设计表格中有3个文本框 -txtName -txtNmail -txtComment
创建数据库“测试” 创建表“ Table1” 和“ Table2”
表1(字段):
表2(字段):
在SQL goto数据库图中。 在两个表之间创建关系
这里Table1的id是主键(自动) 并且Table2的id也是primarykey(auto) id-> id
添加 LINQtoSQLClasses :
现在将sqlDB与Visual Studio连接
然后将所有表放入Linq类。
然后打开aspx.cs
文件并键入代码:
table1 ta = new table1();
ta.name = txtname.Text;
ta.email = txtEmail.Text;
db.table1s.InsertOnSubmit(ta);
Table2 tb = new Table2();
tb.Comments = txtComment.Text;
db.Table_2s.InsertOnSubmit(tb);
db.SubmitChanges();
Response.Write("Data Submit");