gpt4 book ai didi

c# - 将数据存储在表中(SQL)

转载 作者:行者123 更新时间:2023-11-28 23:24:17 26 4
gpt4 key购买 nike

我是这个编程领域的新手,基本上我来自电气领域。现在我学习 SQL 概念。我有一个数据库,该数据库有两个表。我的数据库名称是“MyDataBase”,第一个表名称是“Assets”,然后我的第二个表名称是“AssetAssigneeMapper”。

第一个表列是( Assets )

    assetId int (Identity),
assetName varChar(100),
modelNo varChar(100),
price decimal,
quantity int.

我的第二个表列是 (AssetAssigneeMapper)

    assignId int (Identity),
assetId int(Foreign Key ),
assignedQty int,
employeeName varChar(100).

我通过编码成功地将数据存储在我的第一个表( Assets )中,但是当我尝试将数据存储在第二个表中时,编译跳转到“捕获”部分。

这是我的代码

此代码用于存储第一个表中的数据

try
{
Console.WriteLine("Enter the asset name");
string assetName = (Console.ReadLine()).ToLower();
Console.WriteLine("Enter the model number");
string modelNo = Console.ReadLine();
Console.WriteLine("Enter the price of the asset");
decimal price = decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter the quantity ");
int quantity = int.Parse(Console.ReadLine());
using (var db = new MyDataBaseEntities())
{
db.Assets.Add(new Asset()
{
assetName = assetName,
modelNo = modelNo,
price = price,
quantity = quantity
});
db.SaveChanges();
Console.WriteLine("New asset '{0}' Added in database successfully", assetName);
}
}
catch
{
Console.WriteLine("Enter the proper input");
AddSingleAsset();
}

我将数据存储在第二个表中的代码是

try
{
Console.WriteLine("Enter the asset name to assign");
string assetName = Console.ReadLine().ToLower();

using (var database = new MyDataBaseEntities())
{
var Check = database.Assets.FirstOrDefault
(x => x.assetName == assetName);
if (Check.assetName == assetName)
{
Console.WriteLine("How many asset to be assigned to employee");
string qty = Console.ReadLine();
int quantity;
if (int.TryParse(qty, out quantity))
{
if (Check.quantity >= quantity)
{

Console.WriteLine("Enter the name of the employee");
String employeeName = Console.ReadLine();

database.AssetAssigneeMappers.Add(new AssetAssigneeMapper()
{
assignedQty = quantity,
employeeName = employeeName
});
database.SaveChanges();

Check.quantity = Check.quantity - quantity;
database.SaveChanges();
Console.WriteLine("{0}[{1}]-Quantity has successfully assigned to {2}", assetName, Check.modelNo, employeeName);
}
else
{
Console.WriteLine("Quantity level is lower than your requirment");
}
}
else
{
Console.WriteLine("Given Quantity input is INVALID");
}
}
else
{
Console.WriteLine("Given Asset name is not available in database");
}


}
}
catch
{
Console.WriteLine("Invalid input");
}

当我编译上面的(AssetAssigneeMapper)代码时,我的结果如下

SAMPLE OUTPUT

任何人请指出我做错了什么也建议我正确的方法

最佳答案

我得到了我想要的输出,我在这里所做的是,我将“assetId”定义为“非空”类型。在上面的代码中,我没有添加文本来存储 assetId,所以只有我得到错误的输出。

下面是正确的代码

database.AssetAssigneeMappers.Add(new AssetAssigneeMapper()
{
assignedQty = quantity,
employeeName = employeeName,
assetId=Check.assetId
});
database.SaveChanges();

关于c# - 将数据存储在表中(SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40016210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com