Skip to content

Instantly share code, notes, and snippets.

@ngohungphuc
Created August 2, 2019 08:54
Show Gist options
  • Save ngohungphuc/26e7024256b4f4f7f837761bd38c7722 to your computer and use it in GitHub Desktop.
Save ngohungphuc/26e7024256b4f4f7f837761bd38c7722 to your computer and use it in GitHub Desktop.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")
);
services
.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
)
SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddScoped<Seeder>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seeder seeder)
{
var post = File.ReadAllText(@"wwwroot/post.json");
var comment = File.ReadAllText(@"wwwroot/comment.json");
seeder.Seedit(post, comment);
}
public class Seeder
{
private readonly AppDbContext _context;
public Seeder(AppDbContext context)
{
_context = context;
}
public void Seedit(string postData, string commentData)
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new PrivateSetterContractResolver()
};
List<Post> posts = JsonConvert.DeserializeObject<List<Post>>(postData, settings);
List<Comment> comments = JsonConvert.DeserializeObject<List<Comment>>(commentData, settings);
if (!_context.Posts.Any())
{
_context.AddRange(posts);
_context.SaveChanges();
}
if (!_context.Comments.Any())
{
_context.AddRange(comments);
_context.SaveChanges();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment