Я создал приложение Azure Mobile, а затем загрузил созданный бэкэнд и мобильное приложение. Когда я его запускаю, он успешно получает 2 предмета todo в db. Однако, как только я добавлю пользовательскую модель, как показано ниже, она перестает получать объекты todo в мобильном приложении. Я понятия не имею, что вызывает конфликт.C# Azure Mobile Apps - добавление новой модели не работает
- Если я удалить пользовательскую модель & ссылки, я могу еще раз получить список дел на мобильном приложении
Когда я закомментировать эту строку из DbContext, он снова работает:
//public DbSet<User> Users { get; set; }
запуска:
public partial class Startup
{
public static void ConfigureMobileApp(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
//For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686
config.EnableSystemDiagnosticsTracing();
new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);
// Map routes by attribute
config.MapHttpAttributeRoutes();
// Use Entity Framework Code First to create database tables based on your DbContext
Database.SetInitializer(new AuthApp231Initializer());
// To prevent Entity Framework from modifying your database schema, use a null database initializer
// Database.SetInitializer<AuthApp231Context>(null);
MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
// This middleware is intended to be used locally for debugging. By default, HostName will
// only have a value when running in an App Service application.
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
SigningKey = ConfigurationManager.AppSettings["SigningKey"],
ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
TokenHandler = config.GetAppServiceTokenHandler()
});
}
app.UseWebApi(config);
}
}
public class AuthApp231Initializer : CreateDatabaseIfNotExists<AuthApp231Context>
{
protected override void Seed(AuthApp231Context context)
{
List<TodoItem> todoItems = new List<TodoItem>
{
new TodoItem { Id = Guid.NewGuid().ToString(), Text = "First item", Complete = false },
new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Second item", Complete = false },
};
foreach (TodoItem todoItem in todoItems)
{
context.Set<TodoItem>().Add(todoItem);
}
/*List<User> users = new List<User>
{
new User { Id = Guid.NewGuid().ToString(), Username = "adrian", Password = "supersecret" }
};
foreach (User user in users)
{
context.Set<User>().Add(user);
}*/
base.Seed(context);
}
}
Dat aObjects:
public class User :EntityData
{
public string Username { get; set; }
public string Password { get; set; }
}
Контекст:
public class AuthApp231Context : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to alter your database
// automatically whenever you change your model schema, please use data migrations.
// For more information refer to the documentation:
// http://msdn.microsoft.com/en-us/data/jj591621.aspx
private const string connectionStringName = "Name=MS_TableConnectionString";
public AuthApp231Context() : base(connectionStringName)
{
}
public DbSet<TodoItem> TodoItems { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}
}
Спасибо за ответ. Фактически я выполнил вашу книгу (глава 2), чтобы реализовать аутентификацию. Я следовал всем шагам, но не мог заставить его работать. Также для модели пользователя. DataAnnotations больше недействителен, поэтому я использовал EntityData для пользователя. –
EntityData - это всего лишь реализация ITableData, которая использует Entity Framework. DataAnnotations происходит от Entity Framework. Если вы обновили версию .NETCore Entity Framework (которую вы определенно не должны делать), то это вероятный результат. –