如何在C#中不使用Edmx时使用DbContext?

时间:2014-11-06 05:59:24

标签: c# entity-framework dbcontext

我们可以使用DbContext而无需在项目中添加EDMX数据模型这里是示例代码,我试图在Instance ContextManager DbContext的帮助下保存using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core.Objects.DataClasses; using System.Linq; using System.Text; namespace DbContext_test { public class ContextManager : DbContext { public ContextManager(string connstring) : base(connstring) { } public override int SaveChanges() { //TODO: Write code before saving dataEntity object or fire some event to do so. return base.SaveChanges(); } } public class Instances : EntityObject { public int ID { get; set; } public string InstanceCode { get; set; } public string InstanceName { get; set; } } public class InstanceManager { readonly string ConnectionString; public InstanceManager(string connString) { ConnectionString = connString; } public void SaveInstance(int id, string instanceCode, string instanceName) { SaveInstanceInternal(new Instances { ID = id, InstanceCode = instanceCode, InstanceName = instanceName }); } public void SaveInstance(Instances instance) { SaveInstanceInternal(instance); } private void SaveInstanceInternal(Instances instance) { var contextManager = new ContextManager(ConnectionString); contextManager.Entry(instance); contextManager.SaveChanges(); } } } 类对象1}}。

{{1}}

2 个答案:

答案 0 :(得分:6)

您可以使用代码优先方法而不是edmx方法来实现。

http://www.entityframeworktutorial.net/code-first/what-is-code-first.aspx

答案 1 :(得分:6)

按照这个

1)创建上下文类

 public class SchoolPlusDBContext : DbContext
{
    public SchoolPlusDBContext()
        : base("name=SchoolPlusDBContext")
    {

    }


    public DbSet<CategoryMaster> CategoryMaster { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    } 

}

2)创建课程

public class CategoryMaster
{
   [Key]
    public long CategoryID { get; set; }
   [Required]
    public string CategoryName { get; set; }
     [Required]
    public string CategoryType { get; set; }

}

3)DA用于查询执行

 public class CategoryDA
{

    SchoolPlusDBContext dbContext = new SchoolPlusDBContext();

    public List<CategoryMaster> GetAllCategory()
    {
        return dbContext.CategoryMaster.OrderByDescending(t => t.CategoryID).ToList();
    }

    public bool AddCategory(CategoryMaster master,string UserName)
    {
        try
        {
            master.CreatedBy = UserName;
            master.CreatedOn = System.DateTime.Now;

            dbContext.CategoryMaster.Add(master);
            dbContext.SaveChanges();
        }
        catch
        {
            return false;
        }
        return true;
    }


}

}