2017-03-03 96 views
0

我正在做一个大学的练习,我创建了一个SQL Database并将它链接到Visual Studio中的实体框架帮助下的网格视图。要在数据库上创建一个新条目,我必须填写一些文本字段(例如:名称,库存)。将下拉列表值保存到SQL数据库条目

现在,我知道,从一个文本字段,这取决于它是stringdecimalinteger,我使用以下方法来每个文本字段绑定到相应的部分上的数据库中的表,并且因此保存其值(。 CS代码):

Rugby entry = new Rugby(); 
entry.Stock = int.Parse(txtStock.Text); 
entry.Name = txtName.Text; 

如果我想一个dropdown列表添加到我的代码,并从那里获得的一个值,并将其保存在给定表(类别)中创建新条目,怎么会有我完成以下代码位线:

entry.Category=???(bit that I don't know how to complete) 
+0

你已经把你的EF图表带入VS了吗? – confusedandamused

+0

是的,我有Model.edmx文件,我认为你的意思是@confusedandamused – JGuerra

+0

没有这样的事情作为** SQL数据库** - SQL只是结构化查询语言 - 许多数据库系统使用的语言,但它不是数据库产品。许多东西都是特定于供应商的 - 所以我们真的需要知道**您正在使用的数据库系统**(以及哪个版本)....(请相应地更新标签) –

回答

0

如果你已经把你的EF图表到Visual Studio(您的.edmx文件),而且我理解你的表结构正确,你可以简单地做这样的:

// This will be what you named your entities from your .edmx 
// This object sets up the connection to your entities 
public static myEntities _db = new myEntities(); 

(Auto-Generated Class via .edmx) 
// When you add an .edmx file (database diagram for EF) 
// There is an auto-generated class you are able to use - 
// We are setting this up below. 
EF_Class_Name newDbEntry= new EF_Class_Name(); 


// You can access any property of the class just like any other object 
// property. 
newDbEntry.Stock = int.Parse(txtStock.Text); 
newDbEntry.Name = txtName.Text; 
newDbEntry.Category = dropdown.SelectedValue; 


// Add your new data (essentially an insert) 
_db.EF_Class_Name.Add(newDbEntry); 

// Commit the changes 
_db.SaveChanges(); 
+0

即使我对这个工作的评论中发生的事情感到困惑。谢谢! – JGuerra

+0

@JGuerra有什么我可以添加到我的答案来帮助理解?我现在补充一点,可能会澄清一些东西。 – confusedandamused

+1

感谢您的更新,它的确有助于更好地理解它。对迟交的歉意抱歉。工作过一种享受! – JGuerra

0

Rugby实体也应该有FK财产(CategoryId),这样你可以节省您的下拉列表中的SelectedValue建立关系:

entry.CategoryId=dropdown.SelectedValue; 

这是假设您正在设置您的下拉列表像这种方式:

var categories = (from c in context.Categories 
          select new { c.CategoryId, c.CategoryName }).ToList(); 

// Change this for the real property names 
dropdown.DataValueField = "CategoryId"; 
dropdown.DataTextField = "CategoryName"; 
dropdown.DataSource = categories; 
dropdown.DataBind(); 
+0

对不起,我的无知,但你会如何设置FK属性? @octavioccl – JGuerra

+0

@JGuerra这是你在MSSQL服务器中设置的东西,然后更新你的图表以使其进入。 – confusedandamused

相关问题