微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linq-to-sql – 为什么我的DataContext不会使用SQL Server Compact Edition 4,而不是尝试使用3.5?

我正在玩 SQL Server Compact Edition 4 CTP1,因为我想将它用作低流量网络应用的数据存储.当我尝试使用指定System.Data.sqlServerCe.4.0的连接字符串创建DataContext时(为了使用LINQ To sql),我收到以下错误消息:
Cannot open '|DataDirectory|\data.sdf'. Provider 'System.Data.sqlServerCe.3.5' not installed.

那么为什么我的代码不使用sql CE的第4版?

背景故事:我正在使用Visual Web Developer Express 2010进行开发,但我下载了WebMatrix测试版并使用其设计器创建了包含一些测试数据的sql CE 4 .sdf文件.

使用sqlCeConnection / sqlCeCommand / sqlCeDataReader类,我已经成功创建了一个基本的MVC应用程序,它可以检索测试数据并显示它. sql CE 4二进制文件将复制到应用程序的bin文件夹中.在我的控制器中:

var connectionString = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
var tmp = new Dictionary<string,string>();

using(var conn = new sqlCeConnection(connectionString))
{
    conn.open();

    using (sqlCeDataReader r = new sqlCeCommand("select * from ttest",conn).ExecuteReader())
    {
        while (r.Read())
        {
            tmp.Add(r["id"].ToString(),r["name"].ToString());
        }
    }
}

return View(new Testviewmodel { 
    Items = tmp
});

Web.config中的连接字符串如下:

<add name="Main" connectionString="Data Source=|DataDirectory|\data.sdf" providerName="System.Data.sqlServerCe.4.0" />

这很好用,所以我知道连接字符串是正确的,我已经正确设置了二进制文件等等.所以我想我会尝试一些LINQ To sql的东西,这就是我想要构建真正的应用程序:

[Table(Name = "tTest")]
public class TestEntity
{
    [Column(IsPrimaryKey = true,IsDbGenerated = true)]
    public int ID { get; set; }
    [Column]
    public string Name { get; set; }
}

public class Repository
{
    private Table<TestEntity> testTable;

    public Repository()
    {
        var connectionString = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
        var context = new DataContext(connectionString);
        testTable = context.GetTable<TestEntity>();
    }

    public IQueryable<TestEntity> TestEntities
    {
        get { return testTable;  }
    }
}

然后在控制器中(db是在控制器构造函数中构造的Repository):

var tmp = db.TestEntities.ToDictionary(x => x.ID.ToString(),x => x.Name);

return View(new Testviewmodel { 
    Items = tmp
});

但是当我使用此代码查看页面时,我收到上述错误

Cannot open '|DataDirectory|\data.sdf'. Provider 'System.Data.sqlServerCe.3.5' not installed.

如何强制我的应用使用正确的版本?有人可以帮忙吗?

解决方法

sql Server Compact 4.0不支持LINQ to sql,只有Entity Framework / LINQ to Entities.但是如果你将版本4 sqlCeConnection传递给DataContext构造函数,它实际上会工作!

原文地址:https://www.jb51.cc/mssql/77271.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐