[英]New record using Entity Framework DataLayer Repository Add() Function
I am beginner to Entity Framework and ASP.NET MVC and learning it from online tutorials, I made a class library datalayer ( Student.DataLayer
) first, in which I have a Repository.cs
, where I have all the functions like 我是Entity Framework和ASP.NET MVC的初学者,并从在线教程中学习它,我首先创建了一个类库datalayer(
Student.DataLayer
),其中我有一个Repository.cs
,其中我有所有的函数,如
protected readonly ObjectContext _connection;
public Repository(IConnectionHelper connection)
{
_connection = connection.Connection;
}
public virtual ObjectSet<T> ObjectSet
{
get
{
return
_connection.CreateObjectSet<T>();
}
}
public virtual T Get(Expression<Func<T, bool>> predicate)
{
return ObjectSet.FirstOrDefault(predicate);
}
public virtual T Add(T entity)
{
ObjectSet.AddObject(entity);
Save();
return entity;
}
public virtual void Save()
{
_connection.SaveChanges();
}
in IRepository.cs
I have 在
IRepository.cs
我有
public interface IRepository<T> where T : class
{
T Get(Expression<Func<T, bool>> predicate);
T Add(T entity);
void Save();
}
Now I have add the reference of Student.Datalayer
in the main ASP.NET MVC3 project Student
, so I can access all the functions of datalayer now. 现在我在主ASP.NET MVC3项目
Student
添加了Student.Datalayer
的引用,所以我现在可以访问datalayer的所有功能。
I have a table in database with the name Student
, and it only have student_id
and student_first_name
and student_last_name
columns 我在数据库中有一个名为
Student
的表,它只有student_id
和student_first_name
以及student_last_name
列
So far I have managed to update records in model which are already added 到目前为止,我已经设法更新已添加的模型中的记录
public bool update_name(int id, string newfirstname, string newlastname)
{
var stud = _stu.Get(p => p.student_id == id);
stud.student_first_name = newfirstname;
stud.student_last_name = newlastname;
_stu.Save();
return true;
}
but how to add a new record in the table using _stu.Add()
, I can't figure this out. 但如何使用
_stu.Add()
在表中添加新记录,我无法弄清楚这一点。 I am trying like below. 我在尝试如下。
public bool add_Student(string firstname, string lastname)
{
_stu.Add( //what to do here
return true;
}
I really want to know this way, because using datalayer like this approach, it's very clean. 我真的很想知道这种方式,因为使用像这种方法的数据层,它非常干净。 So please help me
所以请帮助我
The add_Student()
function you have has no dependencies, ie., no parameters. 你拥有的
add_Student()
函数没有依赖关系,即没有参数。 I assume you would need some parameters like the students first and last name, maybe email address, etc. 我假设您需要一些参数,如学生姓名,电子邮件地址等。
And then use that to create a new student: 然后用它来创建一个新学生:
public bool add_Student(string firstname, string lastname)
{
//Requires code to get the new ID,
//unless your ObjectSet classes creates the ID automatically.
int newStudentID = 1;
var s = new StudentObject()
{
id = newStudentID, //may not need to be here
FirstName = firstname,
LastName = lastname
};
_stu.Add(s)
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.