我需要用c#以编程方式创建两个表,这些表将有一些列,其中一个是on ID。 ID必须是一个从1开始的计数器,并且每行总是加1,并且该ID必须是第二个表上的外键。我该怎么做?我已经在互联网上搜索过,但没有找到最终结论。
答案 0 :(得分:0)
您必须创建一个与另一个表B有关系的表A. 所以在表B中将是一个外键指向表A的ID的列。
表A
ID Column1 Column1 . . .
1 name1 value1
2 nam2 value2
表B
ID Column1 Column2 table_A_id . . .
1 name1 value1 1
2 name2 value1 1
3 name3 value1 2
答案 1 :(得分:0)
public class DataStack1
{
[System.ComponentModel.DataAnnotations.Key]
public int id { get; set; }
public string somedata { get; set; }
}
public class DataStack2
{
[System.ComponentModel.DataAnnotations.Key]
public int id { get; set; }
public int DataStack1id { get; set; }
public DataStack1 DataStack1 { get; set; }
public string somedata { get; set; }
}
当您创建DBSets时,Entity Framework将识别此关系。 要创建DBSets,请使用以下代码:
public class DataContext : DbContext
{
public DbSet<DataStack1> DataStack1 { get; set; }
public DbSet<DataStack2> DataStack2 { get; set; }
}
使用以下代码访问表格:
using (var dataset = new DataContext())
{
var Data = dataset.DataStack1.ToList();
}
您可以将以下连接字符串添加到App.config文件中:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data.mdf;Initial Catalog=Data-Project;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
答案 2 :(得分:0)
DataTable table1 =new DataTable();
DataColumn autoIncrement=new DataColumn("AutoIncrement",typeof(System.Int32));
table1.Columns.Add(autoIncrement);
autoIncrement.AutoIncrement=true;
autoIncrement.AutoIncrementSeed=1;
autoIncrement.ReadOnly =true;
DataTable dtEmployee = getEmployeeRecords();
DataTable dtDepartment = getDepartmentRecords();
DataColumn obj_ParentDepartmentID, obj_ChildDepartmentID;
DataSet ds = new DataSet();
ds.Tables.Add(dtDepartment);
ds.Tables.Add(dtEmployee);
obj_ParentDepartmentID = ds.Tables["Department"].Columns["DeptID"];
obj_ChildDepartmentID = ds.Tables["Employee"].Columns["DeptID"];
dtEmployee.Columns.Add("DepartmentName");
DataRelation obj_DataRelation = new DataRelation("dept_reln", obj_ParentDepartmentID, obj_ChildDepartmentID);
ds.Relations.Add(obj_DataRelation);
foreach (DataRow dr_Employee in ds.Tables["Employee"].Rows)
{
DataRow dr_Department = dr_Employee.GetParentRow(obj_DataRelation);
dr_Employee["DepartmentName"] = dr_Department["DeptName"];
}
DataTable dtResult = ds.Tables["Employee"].DefaultView.ToTable(false, "EmployeeID", "EmployeeName", "FatherName", "DepartmentName");