SqlServer教程

AutoCAD中使用EntityFramework连接SqlServerCe数据库

本文主要是介绍AutoCAD中使用EntityFramework连接SqlServerCe数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、需要用到的依赖库如下:

EntityFramework.6.4.4

EntityFramework.SqlServerCompact.6.4.4

Microsoft.SqlServer.Compact.4.0.8876.1

2、app.config需要的配置:

<configSections>
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<  section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>

  <!-- Add the attribute 'codeConfigurationType' to the 'entityFramework' root element to overwrite the global DbConfiguration -->
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
    </providers>
  </entityFramework>

  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SqlServerCe.4.0" />
      <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </DbProviderFactories>
  </system.data>

 3、继承DbContext类,其中sqlce是在app.config里配置的连接字符串,这样就完成了最基本的框架。

public class SqlCeDbContext : DbContext
    {
        public SqlCeDbContext()
            : base("sqlce")
        { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            Database.SetInitializer(null); // 不初始化
            base.OnModelCreating(modelBuilder);
        }
    } 

接下来就通过Linq实现数据访问

// 创建实体类
    public class Customer
    {
        /// <summary>
        /// Gets or sets the username
        /// </summary>
        public string Username { get; set; }
    }

// SqlCeDbContext中增加实体类的数据集
    public DbSet<Customer> Customers { get; set; }

// 调用,返回所有数据
    SQLiteDbContext context = new SQLiteDbContext();
    List<Customer> customers = context.Customers.ToList();
// 返回单个数据
    Customer customer = context.Customers.Where(x => x.Username == "ztcad").FirstOrDefault();

实际系统使用当中会更加复杂,比如封装基本实体类BaseEntity -> EfRepository,支持多数据源IDataProvider -> IEfDataProvider、EfDataProviderFactory,还有迁移、映射、缓存等。

这篇关于AutoCAD中使用EntityFramework连接SqlServerCe数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!