0

If I had a simple model

public class Company
{
        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }
}

How would I convert this model into a SQL Server table with Entity Framework code-first?

1
  • you can generate the entities and the DbContext wiht T4 Templating with json but this is a hardware work and I do not think you want to do that! Commented May 21, 2016 at 19:57

1 Answer 1

1

Answer to your question would actually end up being a full tutorial.

That said, I suggest that you visit the following website and get yourself familiar with Entity Framework Code First concepts:

http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx

Mentioned tutorial has both conceptual overview as well as code samples.

Once you are done with tutorial, you will understand the following code snippet:

public class ApplicationContext : DbContext
{
     public DbSet<Company> Companies { get; set; }
}

Then you need to create adequate migration and apply it to your database which will end up with creation of "Companies" or "Company" table (depending on EF version you are using).

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

5 Comments

Can I use Entity and json.net annatations together?
@Demarily Yes, although it is a bad practice to use same classes as domain models and API models. Your API models should expose only those properties that client apps (i.e. mobile app or JavaScript app) use, and not entire entity model.
It will be an import from the api json data to sql server. Would it still be bad practice?
@Demarily Well if that is only usage case and you have 1:1 mapping of API to SQL, it could go by. But i.e. if your entity class has property IsAdmin and you want to set that programmatically only (through code), exposing that property publicly could result in user setting himself as admin through your API.
Perfect. Thank you for your time. I would have tried the questions myself on my code but my laptop is at the office. I'm just doing research right now. Thank again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.