子晴的编程日记

记录我的编程日记

导航

c#传入类名添加类对应的表数据

 

添加方法:

public int Insert<T>(T model)
where T : class, new()
{
int sucess = 0;
if (model is TempInfo)
{
TempInfo temp = (TempInfo)(object)model;
sucess = InsertUser(temp);
}
if (model is StudentInfo)
{
StudentInfo student = (StudentInfo)(object)model;
sucess = InsertStudent(student);
}
return sucess;
}

调用添加数据方法:

int sucess = 0;
EFEntity entity = new EFEntity();
InsertOprater oprator = new InsertOprater();
TempInfo u = new TempInfo();
u.Name = "zhang.san3";
u.Age = 21;
u.Address = "沈阳市3";
u.Phone = "13066668888";
u.condition = "condition3";
sucess = oprator.Insert<TempInfo>(u);
StudentInfo student = new StudentInfo();
student.StudentName = "通过模型添加数据3";
student.Grades_GradeId = 26;
sucess = oprator.Insert<StudentInfo>(student);
if (sucess > 0)
{
MessageBox.Show("添加数据模块成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("添加数据模块失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private int InsertUser(TempInfo temp)
{
int sucess = 0;
using (EFEntity ef = new EFEntity())
{
ef.TempInfo.Add(temp);
sucess = ef.SaveChanges();
}
return sucess;
}
private int InsertStudent(StudentInfo student)
{
int sucess = 0;
using (EFEntity ef = new EFEntity())
{
ef.StudentInfo.Add(student);
sucess = ef.SaveChanges();
}
return sucess;
}

Temp类

[Table("TempInfo", Schema = "MyData")]
public class Temp
{
[Key]
public int Id { get; set; }
[MaxLength(20)]
public string Name { get; set; }
public int Age { get; set; }
[MaxLength(30)]
public string Phone { get; set; }
[MaxLength(50)]
public string Address { get; set; }
[MaxLength(200)]
public string condition { get; set; }
}

以下是引用生成表的类名

public class MyContext:DbContext
{
public MyContext():base()
{

}
/*
public DbSet<User> User { get; set; }
public DbSet<Temp> Temp { get; set; }
public DbSet<Student> Student { get; set; }
public DbSet<StudentAddress> StudentAddress { get; set; }
public DbSet<Grade> Grade { get; set; }
public DbSet<Course> Course { get; set; }
**/

public DbSet<UserInfo> UserInfo { get; set; }
public DbSet<TempInfo> TempInfo { get; set; }
public DbSet<StudentInfo> StudentInfo { get; set; }
public DbSet<StudentAddressInfo> StudentAddressInfo { get; set; }
public DbSet<GradeInfo> GradeInfo { get; set; }
public DbSet<CourseInfo> CourseInfo { get; set; }
}

posted on 2019-07-15 16:07  子晴的编程日记  阅读(443)  评论(0编辑  收藏  举报