2

I don't understand what is the reason of using OnModelCreating function?

when I can do something like

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int Id { get; set; }

public Int LanguageId { get; set; }
[ForeignKey("LanguageId")]

public Language Language { get; set; }

Maybe I am wrong but when I reads about this,it is explained as it's for Many-to-Many relationship. so why not do something like this.

ICollection<User> Users
0

1 Answer 1

5

For making relationship between entities, we have two options

  1. DataAnnotation (Which you are using)
  2. Fluent API.

When we are using fluent API we need to specify our relationship in this OnModelCreating(DbModelbuilder modelbuilder) method.So when model is created first time they should maintain relationship between entities.

Common Example for using this method is given in this below code snnipet

modelBuilder.Entity<Department>().Property(t => t.Name).HasMaxLength(50);

the same can be achieved using data annotation attribute.

[MaxLength(50)]
public string Name {get;set;}

So if you dont want to use DataAnotation Use Fluent API to serve your purpose.

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.