EF5 Inheritance with code first - ef-code-first

I've multiple smaller versions of classes that maps to single database table
e.g
UserBrief Class:
[Table("Users")]
public partial class UserBrief
{
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
UserAdmin Class
[Table("Users")]
public partial class UserAdmin : UserBrief
{
public int RoleID { get; set; }
}
UserHR Class
[Table("Users")]
public partial class UserHR : UserBrief
{
public string EmailAddress { get; set; }
public string Phone { get; set; }
}
User Class
[Table("Users")]
public partial class User
{
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int RoleID { get; set; }
public string EmailAddress { get; set; }
public string Phone { get; set; }
}
I've multiple bounded contexts. Depending on functionality of context I've used above classes.
If I add single class in context and Ignore all other classes then it works fine.
e.g
public DbSet<UserHR> UserHRs { get; set; }
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Ignore<UserBrief>();
modelBuilder.Ignore<UserAdmin >();
modelBuilder.Ignore<User>();
}
Now if I added UserBrief and UserHRs
It gives error "Invalid column name 'Discriminator'" as EF assumes that this is Table per Hierarchy (TPH) approach.
I've been searching for solution, but can't find how to do this.
Any ideas?
Thanks in advance.

The inherited classes in the POCO objects for the TPH approach should represent sub-types of the class, not just property sections. Having the User table which is a combination of UserHR and UserAdmin breaks this representation.
You could attempt to add a Discriminator property to the User table to fix the error, but I would suggest either just using the Users table with nullable properties or modeling your objects as 1-to-1 relationships:
public class UserBrief
{
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual UserAdmin UserAdmin { get; set; }
public virtual UserHR UserHR { get; set; }
}
public class UserAdmin
{
[Key]
[ForeignKey("UserBrief")]
public int EmployeeID { get; set; }
public int RoleID { get; set; }
public virtual UserBrief UserBrief{ get; set; }
}
public class UserHR
{
[Key]
[ForeignKey("UserBrief")]
public int EmployeeID { get; set; }
public string EmailAddress { get; set; }
public string Phone { get; set; }
public virtual UserBrief UserBrief{ get; set; }
}

Related

Base entity in many to many relationships

I'm trying to implement BaseEntity class.
There i have fields:
Id, CreatedDateTime, UpdatedDateTime, CreatedBy, UpdatedBy.
In my repository class i point this:
public interface IRepositoryBase<TEntity> where TEntity : BaseEntity
Is it will be correct to inherit BaseEntity also in every many-to-many entity?
Like this:
public class OrderDish
{
public int OrderId { get; set; }
public Order Order { get; set; }
public int DishId { get; set; }
public Dish Dish { get; set; }
}
If your BaseEntity looks like this:
public interface BaseEntity
{
DateTime? CreatedDate { get; set; }
DateTime? UpdatedDate { get; set; }
string CreatedBy { get; set; }
string UpdatedBy { get; set; }
}
Create an Entity class from BaseEntity like:
public class Entity : BaseEntity
{
protected Entity(){}
public virtual string CreatedBy { get; set; }
public virtual DateTime? CreatedDate { get; set; }
public virtual string UpdatedBy { get; set; }
public virtual DateTime? UpdatedDate { get; set; }
}
Inherit the other entitites from Entity like:
public class OrderDish : Entity
{
public int OrderId { get; set; }
public Order Order { get; set; }
public int DishId { get; set; }
public Dish Dish { get; set; }
}
You will be able to access the properties this way

Code First Model Definition

I have the following models,do I define it Ok?
User is the main Entity and can have 0..1 to * (zero /one to many relationship ) address.
2.User can have have 0..1 to 1 (one to one userPass )
This is the main table
public class User
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string PhoneWork { get; set; }
public string WorkingAt { get; set; }
public virtual UserPass UserPass { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class ConfigModelDbContext : DbContext
{
public DbSet<User> User { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<UserPass> UserPasses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<User>()
.HasOptional(c => c.Addresses).WithRequired(addresses => new User());
modelBuilder.Entity<User>()
.HasOptional(c => c.UserPass).WithRequired(pass => new User());
}
}
Address Class
public class Address
{
[Key]
[ForeignKey("User")]
public string UserId { get; set; }
public string UserAddress { get; set; }
}
Userpass class
public class UserPass
{
[Key]
[ForeignKey("User")]
public string UserId { get; set; }
public string User { get; set; }
public string Password { get; set; }
}
i also created classes same as above but can it create relationship directly on database table?
at first I offer you to use data annotation instead of fluent api always.
then correct AddressClass like below:
public class Address
{
[Key]
public int Id { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
public string UserId { get; set; }
public string UserAddress { get; set; }
}
This will create Ralationship.
for more details please read Code First DataAnnotations

Entity Framework Table Per Type inheritance with discriminator column

I am using EF5 TPT and thus don't expect a discriminator column. Why is it being created?
The ( simplified) table classes are;
[Table("SalesDocumentHeaders")]
public abstract class SalesDocumentHeader : LoggedEntity
{
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
[Required]
public int CreatedByUserId { get; set; }
[Required]
public virtual DateTime? DocumentDate { get; set; }
[Required]
public String ReferenceNumber { get; set; }
}
[Table("SalesOrders")]
public class SalesOrder : SalesDocumentHeader
{
[Required]
public String CustomerOrderNumber { get; set; }
public DateTime? DeliverBy { get; set; }
public virtual SortableBindingList<SalesOrderLine> Lines { get; set; }
}
public abstract class LoggedEntity
{
public int Id { get; set; }
public Guid RowId { get; set; }
[ConcurrencyCheck]
public int RowVersionId { get; set; }
}
The context contains
public DbSet<SalesOrder> SalesOrders { get; set; }
public DbSet<SalesDocumentHeader> SalesDocumentHeaders { get; set; }
The SalesDocumentHeader table creates with a Discriminator column. What am I doing wrong?
it makes no difference whether SalesDocumentHeader is declared as abstract or not
because I had another class which inherited from SalesDocumentHeader which I forgot to mark with the table attribute

EF codefirst relationships

Could someone show me how to create a relationship in my EF codefirst example - I want a relationship on the Products class that has a many relationship to the Product_Spec class so when I compile the code it will have relationships when the database is generated, and also a relationship for the Specification class related to the Product_Spec
Data Context class
classes:
namespace MvcApplication1.Models
{
public class Department
{
[Key]
public long Id { get; set; }
[Required(ErrorMessage="Please enter a name for the departments.")]
[DataType(DataType.Text)]
public string Name { get; set; }
[DataType(DataType.Text)]
[Required(ErrorMessage = "Please enter a valid url for the department.")]
public string Url { get; set; }
public virtual List<Product> Products { get; set; }
}
public class Product
{
[Key]
public long Id { get; set; }
[ForeignKey("FK_Department_Id")]
public long DepartmentId { get; set; }
[DataType(DataType.Text)]
public string Title { get; set; }
[DataType(DataType.Currency)]
public decimal UnitPrice { get; set; }
[DataType(DataType.Currency)]
public decimal SellPrice { get; set; }
}
public class Product_Spec
{
[ForeignKey("FK_Spec_ProductId")]
public long ProductId { get; set; }
[ForeignKey("FK_Spec_SpecId")]
public long SpecId { get; set; }
}
public class Specification
{
[Key]
public long SpecId { get; set; }
[DataType(DataType.Text)]
[Required(ErrorMessage = "Please enter a product specification type.")]
public string Type { get; set; }
[DataType(DataType.Text)]
[Required(ErrorMessage = "Please enter a product specification value.")]
public string Value { get; set; }
}
}
namespace MvcApplication1
{
public class DataContext : DbContext
{
public DbSet<Department> Department { get; set; }
public DbSet<Product> Product { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>().HasRequired(x => x.Products)
.WithMany().HasForeignKey(x => x.Id).WillCascadeOnDelete(true);
modelBuilder.Entity<Product>().HasOptional(x => x.Product_Specs)
.WithMany().HasForeignKey(x =>x.ProductId) // this lines doesn't work
base.OnModelCreating(modelBuilder);
}
}
}
I think you should set column names in ForeignKey attribute, not constraint names:
public class Product
{
[Key]
public long Id { get; set; }
public long DepartmentId { get; set; }
[DataType(DataType.Text)]
public string Title { get; set; }
[DataType(DataType.Currency)]
public decimal UnitPrice { get; set; }
[DataType(DataType.Currency)]
public decimal SellPrice { get; set; }
[ForeignKey("DepartmentId")]
public virtual Department Department { get; set; }
public ICollection<Product_Spec> ProductSpecs { get; set; }
}
public class Product_Spec
{
public long ProductId { get; set; }
public long SpecId { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product {get; set;}
}
It looks like you're trying to create a Many-Many relationship between Products and Specifications. If that's the case, you don't need to define Product_Spec, using the default conventions, Entity Framework will create your required junction table for you provided you make some alterations to your entities (to define the relationship).
In your case, you could make the following alterations:
public class Product
{
// Your other code
// [ForeignKey("FK_Department_Id")] - Not required, EF will configure the key using conventions
public long DepartmentId { get; set; }
public virtual ICollection<Specification> Specifications { get; set; } // Navigation property for one end for your Product *..* Specification relationship.
}
public class Specification
{
// Your other code
public virtual ICollection<Product> Products { get; set; }
}
When your tables are created, you should see a table with a name like SpecificationProducts, which is the junction table used to hold your many..many Product/Specification relationship.
If you needed to explicitly define this mapping (for example if you had an existing tables), you should be able to do something like this:
modelBuilder.Entity<Product>().
HasMany(s => s.Specifications).
WithMany(p => p.Products).
Map(
m =>
{
m.MapLeftKey("ProductId");
m.MapRightKey("SpecId");
m.ToTable("SpecificationProducts");
});

Model collections of the same class held by several other classes

How do I model the following using Castle ActiveRecord?
I have two classes, Customer and Task.
I would like to reuse a third class, Note, stored in a Collection in each of the Customer and Task classes.
public class Note
{
public int ID { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
public class Customer
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
public class Task
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
I would then like to be able to pass the Notes collection to a Gridview, Listview or Repeater in the relevant ASP.Net page for the Customer or Task classes.
I think what you need is to implement a type hierarchy. You can read about it here.
We settled on the following pattern:
[ActiveRecord]
public class Note
{
[PrimaryKey]
public int ID { get; set; }
[Property]
public string Subject { get; set; }
[Property]
public string Body { get; set; }
[BelongsTo]
public Customer Customer { get; set; }
[BelongsTo]
public Customer Task{ get; set; }
}
[ActiveRecord]
public class Customer
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}
[ActiveRecord]
public class Task
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}

Resources