我是Linq的新手,我正试图在Northwind数据库上搞砸它。我已经在线查看了如何进行插入,但以下鳕鱼似乎不起作用。为什么这些数据不会进入供应商表?
using (LinqDataClassesDataContext northwind = new LinqDataClassesDataContext())
{
Supplier newSupplier = new Supplier
{
SupplierID = northwind.Suppliers.Max(id => id.SupplierID) + 1,
CompanyName = "Doe Electrical",
ContactName = "John Doe",
ContactTitle = "Mr.",
Address = "123 Fake Street",
City = "Dublin",
Region = null,
PostalCode = "123456",
Country = "Ireland",
Phone = "123456789",
Fax = "987654321",
HomePage = "Hello World!"
};
northwind.Suppliers.InsertOnSubmit(newSupplier);
try
{
northwind.SubmitChanges();
Console.WriteLine("Inserted");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
throw;
}
}
程序运行完成,没有例外,但数据未插入。 感谢
我已更新供应商ID
CREATE TABLE [dbo].[Suppliers] (
[SupplierID] INT IDENTITY (1, 1) NOT NULL,
[CompanyName] NVARCHAR (40) NOT NULL,
[ContactName] NVARCHAR (30) NULL,
[ContactTitle] NVARCHAR (30) NULL,
[Address] NVARCHAR (60) NULL,
[City] NVARCHAR (15) NULL,
[Region] NVARCHAR (15) NULL,
[PostalCode] NVARCHAR (10) NULL,
[Country] NVARCHAR (15) NULL,
[Phone] NVARCHAR (24) NULL,
[Fax] NVARCHAR (24) NULL,
[HomePage] NTEXT NULL,
CONSTRAINT [PK_Suppliers] PRIMARY KEY CLUSTERED ([SupplierID] ASC)
);
答案 0 :(得分:-1)
using (var northwind = new DataClassesDataContext())
{
var newSupplier = new Supplier();
//SupplierID = northwind.Suppliers.Max(id => id.SupplierID) + 1,
newSupplier.CompanyName = "Doe Electrical";
newSupplier.ContactName = "John Doe";
newSupplier.ContactTitle = "Mr.";
newSupplier.Address = "123 Fake Street";
newSupplier.City = "Dublin";
newSupplier.Region = null;
newSupplier.PostalCode = "123456";
newSupplier.Country = "Ireland";
newSupplier.Phone = "123456789";
newSupplier.Fax = "987654321";
newSupplier.HomePage = "Hello World!";
northwind.Suppliers.InsertOnSubmit(newSupplier);
try
{
northwind.SubmitChanges();
//get identity id for supplierid
var supplierid = newSupplier.SupplierID.ToString();
Console.WriteLine("Inserted");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
throw;
}
}