2

I use Entity Framework Code First.

I have a class Post with an association to User:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Post 
{
    public int Id { get; set; }
    public string Text{ get; set; }
    public int UserId { get; set; }
    public virtual User User { get; set; }
}

The code above correctly generates primary key (Id) for User and foreign key (UserId) for Post due to Code First Conventions.

But what if I don't want to have navigation property (User) in Post class? Removing that

public virtual User User { get; set; } 

results in foreign key not auto-generated for Post.

Can this be done with Fluent API?

1 Answer 1

3

You can establish the association from the other side:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Post> Posts { get; set; }
}

If you don't want a Posts property either the answer is: no, you can't. The reason is that EF must be able to track the association in the object model in order to insert correct foreign key values when inserting Post objects.

Moreover, you wouldn't be able to associate Posts and Users in your code without at least one navigation property.

Addition

And I forgot to mention that, working code-first, EF looks at associations in the class model to create foreign keys in the database.

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

1 Comment

Thx. My superaim was exactly having no navigation properties. So now I know - it's impossible :)

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.