How to initializing the code-first Entity Framework database in an Azure Mobile Services project

后端 未结 3 934
南方客
南方客 2020-12-11 07:50

I am utterly confused by the use of Entity Frameworks code-first migrations within Azure Mobile Services.

I\'m following the article How to make data model changes t

相关标签:
3条回答
  • 2020-12-11 08:25

    The specific error that you're seeing is due to the fact that EF assumes primary keys are also clustered indexes and there's no way to signal that this isn't the case. Things work when you perform automatic migrations because when the app starts, Mobile Services/Apps registers a custom SqlGenerator that removes the clustered index (along with a few other important things). This custom SqlGenerator isn't used by migrations by default.

    However, you can tell your migration to use this same SqlGenerator by specifying it in the Migrations\Configuration.cs file:

    // Mobile Services namespace:
    // using Microsoft.WindowsAzure.Mobile.Service.Tables
    
    // Mobile Apps namespace:
    // using Microsoft.Azure.Mobile.Server.Tables;
    
    ---<snip>---
    
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            SetSqlGenerator("System.Data.SqlClient", new EntityTableSqlGenerator());
        }
    

    Give that a try. The resulting db should include the CreatedAt trigger and other SQL-specific settings that Mobile Services/Apps expects. Let me know if you bump into issues doing this and I can look further.

    0 讨论(0)
  • 2020-12-11 08:32

    I just tested this and I also get this error when using Update-Database in PMC.

    I'm using Azure Mobile Apps, not Services, but it's the same Entity-Data.

    Starting from an empty table, what works for me is just having an Initial Migration file, a Configuration.cs and the MigrateDatabaseToLatestVersion bit. Then you can just run the application with F5 instead of Update-Database.

    It should create your schema along with your seed.

    0 讨论(0)
  • 2020-12-11 08:39

    After trying every solution I can find, , I found the magic is located in these lines (from the Quickstart project)

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Add(
                   new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                       "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
                base.OnModelCreating(modelBuilder);
            }
    

    (add to your context class)

    This solved the clustered error problem. (I'm working with Azure Mobile Apps not Mobile Services)

    0 讨论(0)
提交回复
热议问题