0

I have a Sqlite database and I have installed Sqlite v1.0.99.0. To create my connection, I am using code first from database, but in the dbContext, in the method when it is used fluent to set the relationships between the entities, the primary key is not set, so I get an error when I try to run my application.

Is there any way that the primary key is set using code first from database to avoid to have to set the primary key in the entities?

Thanks.

1 Answer 1

1

Alas you forgot to show the class that describes your entity nor the DbContext that contains this class.

A good beginner's description can be found in "A beginner's guide to entity framework code first"

Here you can see that if you follow certain conventions you don't have to explicitly define the primary key. Entity framework does this for you.

Quite often you see the example of a database with blogs, where each blog has zero or more posts. The blog and the post will have an Id which is the primary key and the post has a foreign key to the Id of the blog.

If you don't want to specify the properties that contains the primary key, nor the ones that contain the foreign keys, define your classes as follows:

public class Blog
{
    public int Id {get; set;}

    public virtual ICollection<Post> Posts {get; set;}
    ...
}
public class Post
{
    public int Id {get; set;}

    public int BlogId {get; set;}
    public virtual Blog Blog {get; set;}
    ...
}

public class MyDbContext : DbContext
{
    public virtual DbSet<Blog> Blogs {get; set;}
    public virtual DbSet<Post> Posts {get; set;}
}

In the code above, property Id will automatically be the primary key of Blog and Post entities. If desired you can decide to use property names Blog.BlogId and Post.PostId. Personally I don't prefer this because this would mean that all my primary keys have different identifiers.

Property Post.BlogId will automatically be the foreign key of the blog the post belongs to.

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

Comments

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.