现在我已经建立了一个数据库。
Visual Studio2008SP1的ADO.NET实体框架生成了一个类似如下的实体模型:http://img835.imageshack.us/img835/1810/carease15test1ef.png
我创建了一个方法,方法如下:
private void buttonAddPatient_Click(object sender, EventArgs e)
{
using (carease15test1Entities context = new carease15test1Entities())
{
long bnumber = Convert.ToInt32(textBoxToBed.Text);
long rnumber = Convert.ToInt32(textBoxOfRoom.Text);
long bid = (from b in context.bed
where b.bnumber == bnumber
select b.bid).First();
long rid = (from r in context.room
where r.rnumber == rnumber
select r.rid).First();
// Create a new bed, and input its details.
patient p = new patient();
p.pname = textBoxPatient.Text;
p.Bed_bid = bid;
p.bedReference.EntityKey = new EntityKey("carease15test1Entities.bed", "bid", bid);
p.Bed_Room_rid = rid;
p.bed.roomReference.EntityKey = new EntityKey("carease15test1Entities.room", "rid", rid);
context.AddTopatient(p);
try
{
context.SaveChanges();
}
catch (OptimisticConcurrencyException ex)
{
// Resolve the concurrency conflict by refreshing the // object context before re-saving changes.
context.Refresh(System.Data.Objects.RefreshMode.ClientWins, p);
// Save changes.
context.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}所有东西都运行得很好,除了
p.bed.roomReference.EntityKey =新EntityKey("carease15test1Entities.room","rid",rid);
结果是一个NullRefenceException提示“object reference not set to a instance of an object”。
这是我的项目文件。
http://www.mediafire.com/?w3rjjbxbxw6wacv
有人能帮我一下吗?
非常感谢。
发布于 2011-11-01 18:30:49
你应该这样做
p.bedReference.Load()以便加载p.bed的内容。
附注:如果您可以升级到.NET 4.0,它将自动为您完成。
https://stackoverflow.com/questions/7964132
复制相似问题