nem*_*_87 5 c# asp.net-mvc ef-migrations entity-framework-6 asp.net-mvc-5
我正在尝试将新表添加到现有数据库中.该数据库由MVC 5项目自动创建.在尝试了许多不同的事情后,我没有成功将表Post添加到我的数据库中.
当我跑:
PM> Enable-Migrations -ContextTypeName StudentBookApp.Models.PostContext -Force
Run Code Online (Sandbox Code Playgroud)
我收到一条错误说:导航属性'PostText'不是'Post'类型的声明属性.验证它是否未从模型中明确排除,并且它是有效的导航属性.
我不明白这个错误,因为PostText它不是导航属性而且我不确定为什么实体框架认为它是.
这是我的Post类的定义,我在PostContext类的类中也是:
public class Post
{
[Key]
public int PostId { get; set; }
public string PostText { get; set; }
public byte[] ImagePost { get; set; }
public byte[] FilePost { get; set; }
public string TextPost { get; set; }
public string UserId { get; set; }
}
public class PostContext : DbContext
{
static PostContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PostContext>());
}
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new PostConfiguration());
}
}
Run Code Online (Sandbox Code Playgroud)
我还创建了映射类PostConfiguration:
public class PostConfiguration : EntityTypeConfiguration<Post>
{
public PostConfiguration() : base()
{
HasKey(p => p.PostId);
ToTable("Post");
HasRequired(p => p.PostText);
ToTable("Post");
HasOptional(p => p.ImagePost);
ToTable("Post");
HasOptional(p => p.FilePost);
ToTable("Post");
HasOptional(p => p.TextPost);
ToTable("Post");
HasRequired(p => p.UserId);
ToTable("Post");
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试简单地迁移数据库调用:
Enable-Migration
Add-Migration "NewMigration"
Update-Database
Run Code Online (Sandbox Code Playgroud)
但是在启用迁移时,我会提到错误.有人知道我做错了什么吗?
编辑:
这是Web.config文件中的connectionString
<connectionStrings>
<add name="PostContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-StudentBookApp-20150114035149.mdf;Initial Catalog=aspnet-StudentBookApp-20150114035149;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
pys*_*o68 22
我很确定你的实体配置问题.
调用HasOptional()
和HasRequired()
用于指定关系约束.你想要做的是设置属性约束:
Property(c => c.PostText).IsRequired();
Run Code Online (Sandbox Code Playgroud)
请注意,调用ToTable()一次就足够了!
以下是对它的一些解读: 使用Fluent API配置/映射属性和类型
您也可以使用注释属性获得相同的结果:
public class Post
{
[Key]
public int PostId { get; set; }
[Required]
public string PostText { get; set; }
public byte[] ImagePost { get; set; }
public byte[] FilePost { get; set; }
public string TextPost { get; set; }
[Required]
public string UserId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
以下是对此的一些解读: 代码优先数据注释
编辑:
我刚看到你想使用表来存储二进制数据(都是byte []属性).我不建议这样做,并且经常将文件存储在磁盘上更好(例如,更容易实现基于路径的缓存).如果你想坚持这一点,你仍然可能想要阅读这个问题:MVC模型如何使byte []可以为空?
归档时间: |
|
查看次数: |
11321 次 |
最近记录: |