我刚刚在C#中开始了一个简单的项目,并添加了“ADO.NET实体数据模型”
我的问题很简单,我有一个“Lesson”表和一个“User”表以及user_id和lesson.user_id之间的外键。我确实在this msdn tutorial中实现了表模型,但没有说明两个表之间的关系。
这是我的失败代码:
User user = null;
string title = "title";
string content = "content";
using (var db = new Entities())
{
//search for the last user
var query = from b in db.Users
orderby b.RegisterDate descending
select b;
foreach (var item in query.Take(1))
{
user = item;
}
//create lesson
Lesson lesson = new Lesson
{
Content = content,
Grade = "X1",
PostDate = DateTime.Now,
Title = title,
User = user, // user {System.Data.Entity.DynamicProxier.User_1DBAF22....}
UserId = user.ID
};
db.Lessons.Add(lesson);
db.SaveChanges(); //DBUpdateException was unhandled \n Unable to update the EntitySet 'Lessons' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
}
答案 0 :(得分:0)
为数据库表定义主键。