I have a problem with Entity Framework in Asp.net. I want to get the Id value whenever I add a record to the SQL database table. How can I do this? Here is my code:
StoredProcedure
USE [Sapphiresworld]
GO
/****** Object: StoredProcedure [dbo].[addProduct] Script Date: 7/4/2018 10:25:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Proc [dbo].[addProduct]
@title nvarchar(250),
@price nvarchar(50),
@unitID int,
@date nvarchar(50),
@subCategoryID int,
@brandID int,
@vat int,
@discount int,
@picture nvarchar(50),
@stock int
as
declare @MyVal int=0
INSERT into [PRODUCT] values (@title,
@price ,
@unitID,
@date,
@subCategoryID ,
@brandID ,
@vat ,
@discount ,
@picture ,
@stock)
Set @MyVal = @@IDENTITY
Select @MyVal as Val
Here is ClsBrand
public string AddBrand(string brandName)
{
var result = new SapphiresworldEntities().AddBrand(brandName).ToString();
return result;
}
Code against Save Button
protected void Btnsave_Click(object sender, EventArgs e)
{
clsBrand nb = new clsBrand();
string nwBran = nb.AddBrand(relig.Text);
}
After inserting a record, the Id value will automatically populate. You just take the value like from objectname.Id.
一旦您在实体框架中调用保存更改方法,ID 将自动填充(假设您有 ID 作为表中的标识列)
As per the above answers the id value will automatically populate after record will insert.
Here is the example.
your DataModel class ex.
public class MyDataModel
{
[Key]
public int Id {get; set;}
public string TestData {get; set;}
}
and when you are going to insert your data using entity framework use this
public bool SaveMethodInDataBase(MyDataModel myDataModel)
{
MyDataModel result = _dbContext.MyDataModel.Add(myDataModel);
_dbContext.SaveChanges();
}
then this result
will return data with Id. in here _dbContext
is your EntityFrameWork SPContext
if you created.
Try This.
Complete Solution
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public async Task<IActionResult> Create([Bind("Id,Name")] Student student)
{
if (ModelState.IsValid)
{
_context.Add(student);
await _context.SaveChangesAsync();
//Here your Id Value after insert record
int StudentId = student.Id;
return RedirectToAction(nameof(Index));
}
return View(student);
}
Hope you understand and it will be helpful for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.