Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

How to annotate EF model class for the equivalent of HasMany, WithOptional and HasForeignKey

$
0
0

see the full below code.

public partial class TestModel : DbContext
    {
        public TestModel()
            : base("name=TestModel")
        {
        }

        public virtual DbSet<Department> Departments { get; set; }
        public virtual DbSet<Employee> Employees { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Department>()
                .Property(e => e.DepartmentName)
                .IsUnicode(false);

            modelBuilder.Entity<Department>()
                .HasMany(e => e.Employees)
                .WithOptional(e => e.Department)
                .HasForeignKey(e => e.DeptID);

            modelBuilder.Entity<Employee>()
                .Property(e => e.Name)
                .IsUnicode(false);
        }
    }
    public partial class Employee
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ID { get; set; }

        public string Name { get; set; }

        public int? DeptID { get; set; }

        public virtual Department Department { get; set; }
    }

    public partial class Department
    {
        public Department()
        {
            Employees = new HashSet<Employee>();
        }

        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ID { get; set; }

        public string DepartmentName { get; set; }

        public virtual ICollection<Employee> Employees { get; set; }
    }

in the above code relation has been set by fluent configuration. they use HasMany, WithOptional and HasForeignKey. i like to know without fluent configuration how could i achieve the same by annotation at class level.

please show me with a class level example. thanks


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>