【问题标题】:How connect to an existing Azure SQL database with Azure function using Entity Framework Core?如何使用 Entity Framework Core 连接到具有 Azure 功能的现有 Azure SQL 数据库?
【发布时间】:2021-08-16 14:56:20
【问题描述】:

我是 Azure 的初学者,我想使用 Entity Framework Core 在现有的 Âzure SQL 数据库和 Azure 函数(定时器触发)之间建立连接。

我看过很多视频,尝试过很多事情,但我真的无法完成。如果你有什么想法,可以帮帮我吗?

提前致谢。

【问题讨论】:

  • 展示您的尝试总是很有用的,这样其他人就不会提出相同的建议或看到失败的原因。

标签: entity-framework-core azure-functions azure-sql-database


【解决方案1】:

关于问题,请参考以下步骤

   <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.15" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.15">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
  1. 定义数据库上下文

        public class BloggingContext : DbContext
        {
           
            public DbSet<Blog> Blogs { get; set; }
          

        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options.UseSqlServer("<connection string>");
         }

        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { get; set; }

            
        }
  1. 功能码
 [FunctionName("Function1")]
        public static void Run([TimerTrigger("0 */5 * * * *", RunOnStartup = true)] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            using (var db = new BloggingContext())
            {
                log.LogInformation("Inserting a new blog");
                db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                db.SaveChanges();
            }
        }
  1. 执行EF核心迁移
Add-Migration InitialCreate
Update-Database
  1. 测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 2021-10-02
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多