我的数据库看起来像这样。
create table Package
(
PackageID int identity,
PackageName varchar(50) not null,
PackageDiscription varchar(max) not null,
primary key (PackageID)
)
create table Software
(
SoftwareID varchar(50) not null,
SoftwareName varchar(50) not null,
DownloadPath varchar(100) not null,
PackageID int,
Primary key (SoftwareID),
Foreign Key (PackageID) references Package on delete cascade on update cascade
)
我想做的是:
protected void BtnPackageSelect_Click(object sender, EventArgs e)
{
SoftwareTableAdapters.PackageTableAdapter p = new SoftwareTableAdapters.PackageTableAdapter();
SoftwareTableAdapters.SoftwareTableAdapter s = new SoftwareTableAdapters.SoftwareTableAdapter();
foreach(var item in p.GetSelectedPackage(DropDownList1.SelectedValue))
{
string PackageName = item.PackageName;
int PackageID = item.PackageID;
string PackageDiscription = item.PackageDiscription;
Label1.Text = "Name: " + PackageName;
Label1.Visible = true;
Label2.Text = "ID: " + PackageID;
Label2.Visible = true;
Label3.Text = "Discription: " + PackageDiscription;
Label3.Visible = true;
ListBox2.Visible = true;
foreach (var software in s.GetSelectedIndexSoftware(PackageID)) <----- this is there the error come.
{
ListBox2.Items.Add(software.SoftwareName);
}
}
}
方法GetSelectedIndexSoftware(packageID)如下所示:
SELECT SoftwareName
FROM Software
WHERE (PackageID = @PackageID)
我现在进入数据库的所有内容是:
insert into Package values('1', '1')
insert into Package values('2', '2')
insert into Software values('1', '1', '1', null)
insert into Software values('2', '2', '2', null)
insert into Software values('3', '3', '3', null)
insert into Software values('4', '4', '4', null)
所有软件的null都已用1
更新我对编码很新,所以有点迷失..希望有人可以帮助我找到问题
------编辑1 ----- 我现在尝试将软件的创建更改为不允许null,然后创建一个名为not linked的包,其中所有尚未链接到包的软件都将链接到该包。在创建时,它在PackageID中创建为1。 它没有帮助。
------编辑2 ----- 我现在试图在Software表上没有外键。 没有帮助
答案 0 :(得分:2)
我认为您收到错误的原因是您没有为Software表的PackageID分配值。因此,当您在for循环中执行“... s.GetSelectedIndexSoftware(PackageID)”时,您将获得null。在insert语句中,您没有为PackageID分配值。
insert into Software values('1', '1', '1', null)
应该是
insert into Software values('1', '1', '1', n)
其中n是Package表中PackageID列的id值。
如果这不起作用。您可能希望尝试将SoftwareID列作为Software表上的整数标识列。