我正在为大学做练习,我已经创建了一个SQL Database
,并在实体框架的帮助下将其链接到Visual Studio中的网格视图。要在数据库上创建新条目,我必须填写一些文本字段(例如:Name,Stock)。
现在,我知道从文本字段开始,取决于string
,decimal
或integer
,我使用以下内容将每个文本字段绑定到相应的部分数据库中的表,因此保存其值(.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 :(得分: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();
答案 1 :(得分:0)
如果您已经将EF Diagrams引入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();