首页 > 解决方案 > 从列表创建 DataContext而不是来自连接字符串

问题描述

有没有办法System.Data.Linq.DataContextList<T>

MSDN中,必须传递带有任何连接字符串的构造函数来启动对象。

我只是想知道有没有办法打破这个并List<T>通过扩展DataContext或其他东西来创建上下文?

期待类似这样的事情,

Class TestEntity
{
    public int EntityId { get; set; }
    public string EntityName { get; set; }
}

var list = new List<TestEntity>();

list.Add(new TestEntity { EntityId = 1, EntityName = "aaa" });
list.Add(new TestEntity { EntityId = 2, EntityName = "bbb" });

//Creating context on-demand with any available objects rather than external resources (database, file etc.)
var context = new DataContext(list); 

标签: c#linq-to-entities

解决方案


您可以执行类似的操作,但请记住,它将 item.EntityName 作为服务器。

 var list = new List<TestEntity>();

        list.Add(new TestEntity { EntityId = 1, EntityName = "aaa" });
        list.Add(new TestEntity { EntityId = 2, EntityName = "bbb" });

        //Creating context on-demand with any available objects rather than external resources (database, file etc.)
        foreach (var item in list)
        {
            var context = new DataContext(item.EntityName);
            context.CreateDatabase();
        }

输出

Server=aaa;Database=DataContext;Integrated Security=SSPI
Server=bbb;Database=DataContext;Integrated Security=SSPI

推荐阅读