如何将Json从String添加到数据库

时间:2016-06-16 12:07:21

标签: c# json

我不知道如何从字符串中取出json并将其插入我的数据库之后。你能帮助我吗? 我知道json字符串很抱歉。

真的不知道如何把它放在数据库中。实际上我不知道我甚至不知道gdata是否已被填充

namespace Gamer.DataLayer.Migrations
{
    using DomainClasses.Models;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;

    public sealed class Configuration : DbMigrationsConfiguration<Gamer.DataLayer.GamerContext>
    {

        #region
        private string _json = @"{""Games"":[
{
    ""EAN"":""2750026762618"",
    ""GameName"":""Uncharted 4"",
    ""Language"":""en|nl"",
    ""GameGenres"":
    [
        { 
            ""GameId"": ""2750026762618"",
            ""Genre"":{
                ""GenreId"":""1"",
                ""GenreName"":""Actie""}
        },
        {             
            ""GameId"": ""2750026762618"",
            ""Genre"":{
                ""GenreId"":""2"",
                ""GenreName"":""Avontuur""}
        },
        {             
            ""GameId"": ""2750026762618"",
            ""Genre"":{
                ""GenreId"":""9"",
                ""GenreName"":""Role Playing Game""}
        },
        { 

            ""GameId"": ""2750026762618"",
            ""Genre"":{
                ""GenreId"":""10"",
                ""GenreName"":""Shooter""}
        }
    ],
    ""PlatformGames"":
    [
        {
            ""GameId"":""2750026762618"",
            ""Platform"":{
                ""PlatformId"":""2"",
                ""PlatformName"":""Playstation 4""},                            
            ""Price"":""59.99""
        }   
    ]
},
{
    ""EAN"":""5030944112878"",
    ""GameName"":""Fifa 16"",
    ""Language"":""en"",
    ""GameGenres"":
    [
        { 
            ""GameId"": ""5030944112878"",
            ""Genre"":{
                ""GenreId"":""1"",
                ""GenreName"":""Actie""}
        },
        {             
            ""GameId"": ""5030944112878"",
            ""Genre"":{
                ""GenreId"":""12"",
                ""GenreName"":""Sport""}
        }
    ],
    ""PlatformGames"":
    [
        {
            ""GameId"":""5030944112878"",
            ""Platform"":{
                ""PlatformId"":""1"",
                ""PlatformName"":""PC""},                            
            ""Price"":""34.99""
        },
        {
            ""GameId"":""5030944112878"",
            ""Platform"":{
                ""PlatformId"":""2"",
                ""PlatformName"":""Playstation 4""},                            
            ""Price"":""39.99""
        },
        {
            ""GameId"":""5030944112878"",
            ""Platform"":{
                ""PlatformId"":""3"",
                ""PlatformName"":""Xbox One""},                            
            ""Price"":""39.99""
        } 
    ]
},
{
    ""EAN"":""5030948112294"",
    ""GameName"":""De Sims 4"",
    ""Language"":""nl"",
    ""GameGenres"":
    [
        { 
            ""GameId"": ""5030948112294"",
            ""Genre"":{
                ""GenreId"":""11"",
                ""GenreName"":""Simulatie""}
        }
    ],
    ""PlatformGames"":
    [
        {
            ""GameId"":""5030948112294"",
            ""Platform"":{
                ""PlatformId"":""1"",
                ""PlatformName"":""PC""},                            
            ""Price"":""71.08""
        }
    ]
},
{
    ""EAN"":""5030949112576"",
    ""GameName"":""Star Wars Battlefront"",
    ""Language"":""en"",
    ""GameGenres"":
    [
        { 
            ""GameId"": ""5030949112576"",
            ""Genre"":{
                ""GenreId"":""2"",
                ""GenreName"":""Avontuur""}
        },
        { 
            ""GameId"": ""5030949112576"",
            ""Genre"":{
                ""GenreId"":""10"",
                ""GenreName"":""Shooter""}
        }
    ],
    ""PlatformGames"":
    [
        {
            ""GameId"":""5030949112576"",
            ""Platform"":{
                ""PlatformId"":""1"",
                ""PlatformName"":""PC""},                            
            ""Price"":""24.99""
        },  
        {
            ""GameId"":""5030949112576"",
            ""Platform"":{
                ""PlatformId"":""2"",
                ""PlatformName"":""Playstation 4""},                            
            ""Price"":""24.99""
        },
        {
            ""GameId"":""5030949112576"",
            ""Platform"":{
                ""PlatformId"":""3"",
                ""PlatformName"":""Xbox One""},                            
            ""Price"":""34.99""
        }     
    ]
},
{
    ""EAN"":""5055856403357"",
    ""GameName"":""Doom"",
    ""Language"":""en"",
    ""GameGenres"":
    [
        { 
            ""GameId"": ""5055856403357"",
            ""Genre"":{
                ""GenreId"":""1"",
                ""GenreName"":""Actie""}
        }
    ],
    ""PlatformGames"":
    [
        {
            ""GameId"":""5055856403357"",
            ""Platform"":{
                ""PlatformId"":""1"",
                ""PlatformName"":""PC""},                            
            ""Price"":""49.99""
        },  
        {
            ""GameId"":""5055856403357"",
            ""Platform"":{
                ""PlatformId"":""2"",
                ""PlatformName"":""Playstation 4""},                            
            ""Price"":""59.99""
        },
        {
            ""GameId"":""5055856403357"",
            ""Platform"":{
                ""PlatformId"":""3"",
                ""PlatformName"":""Xbox One""},                            
            ""Price"":""59.99""
        }     
    ]
},
{
    ""EAN"":""5060146463188"",
    ""GameName"":""Minecraft Story Mode"",
    ""Language"":""nl"",
    ""GameGenres"":
    [
        { 
            ""GameId"": ""5060146463188"",
            ""Genre"":{
                ""GenreId"":""2"",
                ""GenreName"":""Avontuur""}
        }
    ],
    ""PlatformGames"":
    [
        {
            ""GameId"":""5060146463188"",
            ""Platform"":{
                ""PlatformId"":""2"",
                ""PlatformName"":""Playstation 4""},                            
            ""Price"":""30.99""
        },  
        {
            ""GameId"":""5060146463188"",
            ""Platform"":{
                ""PlatformId"":""3"",
                ""PlatformName"":""Xbox One""},                            
            ""Price"":""31.99""
        },
        {
            ""GameId"":""5060146463188"",
            ""Platform"":{
                ""PlatformId"":""4"",
                ""PlatformName"":""Wii U""},                            
            ""Price"":""39.99""
        }     
    ]
},
{
    ""EAN"":""5055856406136"",
    ""GameName"":""Fallout 4"",
    ""Language"":""en"",
    ""GameGenres"":
    [
        { 
            ""GameId"": ""5055856406136"",
            ""Genre"":{
                ""GenreId"":""1"",
                ""GenreName"":""Actie""}
        },
        { 
            ""GameId"": ""5055856406136"",
            ""Genre"":{
                ""GenreId"":""2"",
                ""GenreName"":""Avontuur""}
        },
        { 
            ""GameId"": ""5055856406136"",
            ""Genre"":{
                ""GenreId"":""5"",
                ""GenreName"":""Open wereld""}
        },
        { 
            ""GameId"": ""5055856406136"",
            ""Genre"":{
                ""GenreId"":""9"",
                ""GenreName"":""Role Playing Game""}
        },
        { 
            ""GameId"": ""5055856406136"",
            ""Genre"":{
                ""GenreId"":""10"",
                ""GenreName"":""Shooter""}
        }
    ],
    ""PlatformGames"":
    [
        {
            ""GameId"":""5055856406136"",
            ""Platform"":{
                ""PlatformId"":""1"",
                ""PlatformName"":""PC""},                            
            ""Price"":""114.4""
        },  
        {
            ""GameId"":""5055856406136"",
            ""Platform"":{
                ""PlatformId"":""2"",
                ""PlatformName"":""Playstation 4""},                            
            ""Price"":""264.99""
        },
        {
            ""GameId"":""5055856406136"",
            ""Platform"":{
                ""PlatformId"":""3"",
                ""PlatformName"":""Xbox One""},                            
            ""Price"":""114.99""
        }     
    ]
}
]
}";
        #endregion
        public Configuration()
        {
            // TODO:configure migrations 
        }

        protected override void Seed(Gamer.DataLayer.GamerContext context)
        {
            // TODO:
            // Create a class GamerData to store a list of Games 
            // Deserialize the JSON string to a GamerData object (call this object gdata)

        var gdata = JsonConvert.DeserializeObject<GamerContext>(_json);
            foreach (var game in gdata.Games)
            {

                foreach (var gameGenre in game.GameGenres)
                {
                    Genre myGenre = context.Genres.Where(g => g.GenreId == gameGenre.GenreId).FirstOrDefault();
                    if (myGenre != null)
                        gameGenre.GenreId = myGenre.GenreId;
                }
                foreach (var platformGame in game.PlatformGames)
                {
                    Platform myPlatform = context.Platforms.Where(p => p.PlatformId == platformGame.Platform.PlatformId).FirstOrDefault();
                    if (myPlatform != null)
                        platformGame.Platform = myPlatform;
                }


                // Add the data to your database           
            }
        }
    }


}

更多信息

GamerContext

using Gamer.DomainClasses.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gamer.DataLayer
{
    public class GamerContext : DbContext
    {
        public GamerContext() : base("Gamer")
        { }
        public DbSet<Game> Games { get; set; }
        public DbSet<Genre> Genres { get; set; }
        public DbSet<PlatformGame> PlatformGames { get; set; }
        public DbSet<Platform> Platforms { get; set; }
        public DbSet<GameGenre> GameGenres { get; set; }

    }
}

我的模特(留下使用)

游戏

namespace Gamer.DomainClasses.Models
{
    public class Game
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Required(ErrorMessage = "Key is required")]
        public string EAN { get; set; }
        public string GameName { get; set; }
        public string Language { get; set; }

        public virtual ICollection<PlatformGame> PlatformGames { get; set; }
        public virtual ICollection<Genre> Genres { get; set; }
        public virtual ICollection<Genre> GameGenres { get; set; }
    }
}

GameGenre

namespace Gamer.DomainClasses.Models
{
    public class GameGenre
    {
        [Key, ForeignKey("Game")]
        [Required(ErrorMessage = "Key is required")]
        public string EAN { get; set; }
        [Key, ForeignKey("Genre")]
        [Required(ErrorMessage = "Key is required")]
        public int GenreId {get;set;}

        public virtual ICollection<Genre> Genre { get; set; }
    }
}

类型

namespace Gamer.DomainClasses.Models
{
    public class Genre
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Required(ErrorMessage = "Key is required")]
        public int GenreId { get; set; }
        public string GenreName { get; set; }

        public virtual ICollection<Game> Games { get; set; }
    }
}

平台

namespace Gamer.DomainClasses.Models
{
    public class Platform
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Required(ErrorMessage = "Key is required")]
        public int PlatformId { get; set; }
        public string PlatformName { get; set; }

        public virtual ICollection<PlatformGame> PlatformGames { get; set; }
    }
}

PlatformGame

namespace Gamer.DomainClasses.Models
{
    public class PlatformGame
    {
        [Key, ForeignKey("Platoform")]
        [Required(ErrorMessage = "Key is required")]
        public int PlatformId { get; set; }
        [Key, ForeignKey("Game")]
        [Required(ErrorMessage = "Key is required")]
        public string EAN { get; set; }
        public float Price { get; set; }

        public virtual Game Game { get; set; }
        public virtual Platform Platform { get; set; }
    }
}

的Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Gamer-20160510103314.mdf;Initial Catalog=aspnet-Gamer-20160510103314;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

当我在软件包管理器控制台中尝试更新数据库时

PM> update-database -verbose
Using StartUp project 'Gamer'.
Using NuGet project 'Gamer'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'aspnet-Gamer-20160510103314' (DataSource: (LocalDb)\MSSQLLocalDB, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
You can use the Add-Migration command to write the pending model changes to a code-based migration.

1 个答案:

答案 0 :(得分:1)

  protected override void Seed(Gamer.DataLayer.GamerContext context)
    {
        GamerData gdata = JsonConvert.DeserializeObject<GamerData>(_json);

        foreach (var game in gdata.Games)
        {
            foreach (var gameGenre in game.GameGenres)
            {
                Genre myGenre = context.Genres.Where(g => g.GenreId == gameGenre.Genre.GenreId).FirstOrDefault();
                if (myGenre != null)
                    gameGenre.Genre = myGenre;
            }
            foreach (var platformGame in game.PlatformGames)
            {
                Platform myPlatform = context.Platforms.Where(p => p.PlatformId == platformGame.Platform.PlatformId).FirstOrDefault();
                if (myPlatform != null)
                    platformGame.Platform = myPlatform;
            }

            context.Games.Add(game);
            context.SaveChanges();       
        }

    }

老师忘了添加数据库的布局,所以你必须猜测种子方法中的变量。