[英]Help creating a Windows Form for an Entity who has a reference to a different Entity
這是方案(ADO.NET實體框架和C#)。
String name;
Address addr;
String street;
String city;
**這不是真正的代碼,但是您可以得到圖片*
我正在嘗試創建一個對用戶來說平整的Windows窗體。 換句話說,該表單將具有四個字段(名稱,地址,街道,城市),並且當用戶單擊bindingSourceNavigator中的“添加”按鈕時,我想創建一個新的Contact
實例,以使Contact.addr
為引用到一個新創建的Address
。
如果僅使用對象,這將很簡單,但是我試圖在支持Address
的表中創建新行。
到目前為止,這是我嘗試過的:
private void contactBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
Contact newContact = new Contact();
Address newContactAddr = new Address();
newContact.Address = newContactAddr;
newContactAddr.Contacts.Add(newContact);
//I realize I don't need the Contact list reference in Address,
//but VS2010 created it, so I'm just adding the new Contact to
//the list for now.
e.NewObject = newContact;
}
private void contactBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
contactBindingSource.EndEdit();
context.SaveChanges(); //throws UpdateException
}
一些背景: Form具有Contact
的綁定源,並且此方法是創建新Contact
時的事件處理程序。 我在MSDN上讀到,這是在將對象實際添加到BindingSource之前對其進行修改的方式。 context
是指我的實體模型。
會發生什么:單擊添加按鈕時,我可以輸入聯系信息。 但是,當我單擊保存按鈕時,我得到了UpdateException
。 我懷疑這是因為我沒有正確創建Address
,而是對ADO.NET框架(和一般的.NET編程)不熟悉,所以我並不真正知道執行此操作的正確方法。
一個例子:我有3個表,Users,UserRoles和Roles。
當我創建一個用戶時,我希望該用戶獲得一個角色,然后我會做
using(DatabaseEntities db = new DatabaseEntities())
{
//creates the user and add the properties except roles
Users user = new Users();
user.username = "Test";
//get an existing role
var role = db.Roles.SingleOrDefault(r => r.roleName == "User");
//adds the userid and roleid in to userRoles
user.Roles.Add(role);
db.Users.AddObject(user);
//saves it to the db
db.SaveChanges();
}
因此,為了使其在您的示例中起作用,您首先需要在使用數據庫之前將其中一個插入數據庫,以便將另一個對象以及該行保存到將它們鏈接在一起的表中。
我希望這個簡單的例子對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.