我有一些 C# 中的 Entity Framework REST 服务,可以从 SQL 服务器获取数据。这些服务将托管在 Azure 上。
无法打开数据库进行远程连接,我不希望每个查询都通过服务总线中继,并且我无法在 Azure 中托管数据库。
有没有办法只通过服务总线连接到数据库,然后将实体加载到 Azure 上的内存中,然后查询就可以与之相反?
我正在尝试以下内容:
public class ATPublicRestContext : DbContext
{
public ATPublicRestContext() : base("name=WEBEntities")
{
//do something here to call the dbcontext through a service bus?
//Is that even possible
//or somehow get base("name-WEBEntities") to call the service bus
//binding instead of the connection string to the DB?
}
}
最佳答案
我将发布另一个答案,因为您似乎坚决不允许跨混合连接的所有查询。然而,这样做的可行性实际上取决于数据量及其更改频率。
您可以在启动时轻松地将实体缓存到内存中。因此,当您的应用程序启动时,它将访问数据库并填充这些集合。然后,您的实际 api Controller 将查询这些集合,而不是数据库。 对于小型数据(大部分是静态数据)来说,这是一种非常标准的方法,但对于经常更改的大量数据来说,这是一种相当标准的方法。
潜在问题:
- 您能否合理地将所有这些数据放入内存中?
- 您是否需要横向扩展 API?如果是这样,现在您需要内存中多个位置的多个数据副本。
- 数据多久更改一次?如果有任何更改,您需要使内存中的数据失效并从数据库重新加载。
对其进行切片的另一种方法是不在启动时加载它,而是跟踪已加载的实体,以便第一个请求可以触发加载。
但是,就像我在第一个答案中所说的那样,在执行此类操作之前,我确实会尝试证明混合连接是一个问题。但是,这是完成您似乎想做的事情的一种方法。
更新:
根据您的评论,总体思路如下:在启动代码中的某个位置,您将调用一个方法来填充实体集合。这些可能只是类中包含的通用列表,如下所示:
// in your startup code
EntityRepository.SaturateEntities();
...
// here is the entity repo
public class EntityRepository
{
public static List<SomeEntity> SomeEntities { get; private set; }
public static List<SomeOtherEntity> SomeOtherEntities { get; private set; }
public static void SaturateEntities()
{
// _db is assumed to be your entity framework context
// ToList() will actually execute the query and return the results
SomeEntities = _db.SomeEntities.ToList();
SomeOtherEntities = _db.SomeOtherEntities.ToList();
}
}
现在,在 API Controller 中,您将查询 EntityRepository 中的列表,而不是查询数据上下文。有很多不同的方法可以做到这一点,但希望这能为您提供总体思路。此外,您可以等到第一个请求,而不是在启动时加载所有内容。因此,存储库只会跟踪哪些列表已初始化,并且仅在需要时才加载它们。
关于c# - Azure 中的 Entity Framework REST 服务 - 远程获取实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50261932/