1

I have no clue how to get the json out of the string and insert it into my database after. Could you guys help me out? I know the json string is big sorry for that.

Have really no idea how to put it in the database. Actually i have no idea of i even have no idea if gdata is filled

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           
            }
        }
    }


}

More info

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; }

    }
}

My Models(Left the usings)

Game

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; }
    }
}

Genre

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; }
    }
}

Platform

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>

When i try Update-database in Package manager console

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.
2
  • I dont see anywhere you inserting data into the database Commented Jun 16, 2016 at 12:11
  • I know i have no idee how thats why i ask it Commented Jun 16, 2016 at 12:12

1 Answer 1

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();       
        }

    }

The teacher forgot to add the layout of the database so you had to guess it on the variables you got in the seed method.

Sign up to request clarification or add additional context in comments.

3 Comments

We had db layout But when i post all my db models its way to big
I would suggest to put SaveChanges() outside of the loop.
doesn't make my database:(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.