Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何添加表并将数据保存到现有数据库_C#_Entity Framework_Ef Code First - Fatal编程技术网

C# 如何添加表并将数据保存到现有数据库

C# 如何添加表并将数据保存到现有数据库,c#,entity-framework,ef-code-first,C#,Entity Framework,Ef Code First,我使用代码优先的方法创建了一个数据库(创建了“User.mdf”文件,其中包括一个名为“users”的表) 我添加了一个新模型: public class Picture { public int pictureId { get; set; } public int userId { get; set; } public string pictureUrl { get; set; } } public class PictureDBContext : DbContext

我使用代码优先的方法创建了一个数据库(创建了“User.mdf”文件,其中包括一个名为“users”的表)

我添加了一个新模型:

public class Picture
{
    public int pictureId { get; set; }
    public int userId { get; set; }
    public string pictureUrl { get; set; }
}

public class PictureDBContext : DbContext
{
    public DbSet<Picture> Pictures { get; set; }
}
我希望它能为图片创建一个新的表(因为它在用户模型中工作)

让“EF魔术”也了解这个模型需要什么 以及在现有数据库中创建和添加图片表? 您将很高兴得到一个答案,其中包含将数据保存到新表的正确方法,并尽可能少做解释。

您可能会收到一个错误,因为迁移已关闭

您可以编写自己的迁移来添加新表,也可以先使用EF代码的自动迁移功能

如果您想编写自己的迁移代码,您可以在本博客上自行阅读:

如果要启用自动迁移。您可以添加这个配置类,它应该可以做到这一点

internal sealed class PictureDBContextConfiguration : DbMigrationsConfiguration<PictureDBContext>
{
    public PictureDBContextConfiguration()
    {
        AutomaticMigrationsEnabled = true; // This will allow CodeFirst to create the missing tables/columns
        AutomaticMigrationDataLossAllowed = true;  //This will allow CodeFirst to Drop column or even drop tables
    }
}
内部密封类PictureDBContextConfiguration:DmbigrationsConfiguration
{
公共PictureDBContextConfiguration()
{
AutomaticMigrationsEnabled=true;//这将允许CodeFirst创建缺少的表/列
AutomaticMiggerationDataLossAllowed=true;//这将允许CodeFirst删除列,甚至删除表
}
}

您的问题到底是什么?有些东西不起作用了吗?我想标题作为一个问题就足够了,但我会编辑邮件,把问题也包括进去。谢谢你的回答。已将您的代码添加到“我的图片”类中,但表仍然没有创建。我知道我得到的图片对象是正确的,那么我的代码是:
if(ModelState.IsValid){db.Pictures.Add(curentImage);db.SaveChanges();}
可以吗?我可以看到watch窗口,但没有异常没有得到任何异常(或者我没有在正确的位置查找…)。一切似乎都很好,但新桌子拒绝诞生。。。有什么地方我可以把这个项目寄给你吗?(如果按照StackOverflow的规则和你的看法可以的话)我是一个初学者,这就是为什么我甚至不知道我做错了什么。正确的做法是创建模型,然后运行更新数据库(当然还启用了迁移…),它将为您带来所有的好处。
internal sealed class PictureDBContextConfiguration : DbMigrationsConfiguration<PictureDBContext>
{
    public PictureDBContextConfiguration()
    {
        AutomaticMigrationsEnabled = true; // This will allow CodeFirst to create the missing tables/columns
        AutomaticMigrationDataLossAllowed = true;  //This will allow CodeFirst to Drop column or even drop tables
    }
}