1

Just wondering if it was possible to add Data Annotations to a class referenced from a class library which has no reference on EntityFramework.

For example Project.Data.Entities library

public class User {
    public long Id { get; set; }
    public string UserName { get; set; }
}

Project.Data.Repositories.EntityFramework references Project.Data.Entities library. How can I add the Data Annotations regarding Key properties, Column names, Table names, etc.?

1 Answer 1

2

There are fluent APIs for this purpose.

EDIT

About your mapping you have to override OnModelCreating

public class TestContext : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<User>()
            .ToTable("user")
            .HasKey(_ => _.Id);

        modelBuilder.Entity<User>()
            .Property(_ => _.Id).HasColumnName("id");

        modelBuilder.Entity<User>()
            .Property(_ => _.UserName).HasColumnName("username"); // Add also HasMaxLength here
    }
}

(if your database already exists and it's not created by EF on your model you need to disable also migrations)

EDIT

If you installed SQL Server with a CI codepage, column name casing is not important. So you need only to specify HasMaxLength

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

5 Comments

[Table("user")] public class User { [Key] [Column("id")] public long Id { get; set; } [Column("username")] public string UserName { get; set; } } How can I achieve this using fluent API knowing that my entities need only to be mapped to an existing database schema?
Ok, but I feel this to be kind of overkill to set up for every entity. And we haven't talked about foreign keys yet! Data annotations seemed much cleaner and concise...is there absolutely no way of using them?
No way with data annotation (or better, you can add attributes in the same way of fluent API so fluent API is better). About fluent API, there are different things that you can't do with data annotation (most of them on relationships) so sometimes you have to use them.
Just be cautioned, using somebody else's classes for your entities can get you into some complications. Use with care.
The entities library is designed by me. I put them in a different library just to adhere to design best-practices like separation of concerns and reusability of code.

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.