Entity Framework Code First Map (Linked) Table? - entity-framework

I'm working with the EF code first approach and want to add a link (map) table. I am working off the below example and get the following error:
System.Data.Entity.Edm.EdmEntityType: : EntityType 'EmployeeDepartmentLink' has no key defined. Define the key for this EntityType.
Problem is I dont want a key on this table it just maps the two tables together:
public class Employee
{
[Key()]
public int EmployeeID;
public string Name;
}
public class Department
{
[Key()]
public int DepartmentID;
public string Name;
}
public class EmployeeDepartmentLink
{
public int EmployeeID;
public int DepartmentID;
}
I have tried a variety of things like adding the "[Key()]" attribute but it doesn't make sense for it to be used, and which field do I add it to? I am wondering if this sort of table model is even supported?

You are trying to make a "Many to Many" mapping.
To perform this, write this code:
public class Employee
{
[Key]
public int EmployeeId;
public string Name;
public List<Department> Departments { get; set; }
public Employee()
{
this.Departments = new List<Department>();
}
}
public class Department
{
[Key]
public int DepartmentId;
public string Name;
public List<Employee> Employees { get; set; }
public Department()
{
this.Employees = new List<Employee>();
}
}
then, in your DbContext:
public class YourContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
public YourContext() : base("MyDb")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>().
HasMany(c => c.Employees).
WithMany(p => p.Departments).
Map(
m =>
{
m.MapLeftKey("DepartmentId");
m.MapRightKey("EmployeeId");
m.ToTable("DepartmentEmployees");
});
}
}

For M:M relationship you have to create your join (link) class is as below.
public class EmployeeDepartmentLink
{
[Key, Column(Order = 0)]
public int EmployeeID;
[Key, Column(Order = 1)]
public int DepartmentID;
}
For more information check Create code first, many to many
I hope this will help to you.

Related

EF Core - hierarchy using Composite Design Pattern and CTE

I want to create a catalog products. There may be catalogs or products on each node.
I decided to use the composite design pattern.
I will download the node with the children using CTE. Unfortunately there was a problem, because EF Core doesn't add parentId in the CategoryProducts table.
Additionally the class (Category as my Composite) has its own CategoryDetails class, (Product as my Leaf) has its own ProductDetails class.
How do I configure EF Core to recursively get nodes from the tree?
Is CTE a good idea?
public enum CategoryProductType
{
Category,
Product
}
public abstract class CategoryProduct
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public CategoryProductType Type { get; private set; }
protected CategoryProduct(Guid id, string name, CategoryProductType type)
{
Id = id;
Name = name;
Type = type;
}
}
public class Category : CategoryProduct
{
public string Code { get; private set; }
public CategoryDetails CategoryDetails { get; private set; }
private ICollection<CategoryProduct> _children { get; set; } = new Collection<CategoryProduct>();
public IEnumerable<CategoryProduct> Children => _children;
public Category(Guid id, string name, string code)
: base(id, name, CategoryProductType.Category)
{
Code = code;
}
}
public class CategoryDetails
{
public Guid CategoryId { get; private set; }
public Category Category { get; private set; }
public string Description { get; private set; }
private CategoryDetails() { }
public CategoryDetails(Category category, string description)
{
Category = category);
Description = description);
}
}
public class Product : CategoryProduct
{
public string Index { get; private set; }
public ProductDetails ProductDetails { get; private set; }
public Product(Guid id, string name, string index)
: base(id, name, CategoryProductType.Product)
{
SetIndex(index);
}
}
EF Core Setting:
Unfortunately I don't know anything about CTE Recursion.
However, this is an example on how I modeled a hierarchical structure (i.e. a tree) with EF Core, hopefully it can help you.
public class TreeNode
{
public int TreeNodeId { get; private set; }
public int? ParentTreeNodeId { get; set; }
public TreeNode ParentTreeNode { get; set; }
public List<TreeNode> ChildrenTreeNodes { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TreeNode>(entity =>
{
entity.HasOne(n => n.ParentTreeNode)
.WithMany(n => n.ChildrenTreeNodes)
.HasForeignKey(n => n.ParentTreeNodeId);
});
}

WCF + EF return object with FK

I am facing following issue: I have ProductOrder class which has ProductId as foreign key to Product class. When I invoke following method:
public IEnumerable<ProductOrder> GetOrders()
{
return OddzialDb.ProductOrders;
}
Orders are associated with Product so I can write something like this:
OddzialDb.ProductOrders.First().Product.Name;
but when it reaches Client it turns out that there is no association with Product which is null (only ProductId is included). In DbContext I have set
base.Configuration.ProxyCreationEnabled = false;
base.Configuration.LazyLoadingEnabled = false;
On the WCF Service side auto-generated by EF ProductOrder class looks as follows:
public partial class ProductOrder
{
public int Id { get; set; }
public Nullable<int> ProductId { get; set; }
public int Quantity { get; set; }
public virtual Product Product { get; set; }
}
What happens that it looses connections with tables associated by foreign keys?
Make your relationship virtual as in the example:
public class ProductOrder
{
public int Id { get; set; }
public virtual Product Product { get; set; }
public int ProductId { get; set; }
}
By turning your relationship virtual, the Entity Framework will generate a proxy of your ProductOrder class that will contain a reference of the Product.
To make sure it will work, Product also has to contain reference to ProductOrder:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProductOrder> ProductOrders { get; set; }
}
Set these variables true on your DbContext:
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
On your WCF application, add the following class, which will allow for proxy serialization:
public class ApplyDataContractResolverAttribute : Attribute, IOperationBehavior
{
public ApplyDataContractResolverAttribute()
{
}
public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
{
}
public void ApplyClientBehavior(OperationDescription description, System.ServiceModel.Dispatcher.ClientOperation proxy)
{
DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior =
description.Behaviors.Find<DataContractSerializerOperationBehavior>();
dataContractSerializerOperationBehavior.DataContractResolver =
new ProxyDataContractResolver();
}
public void ApplyDispatchBehavior(OperationDescription description, System.ServiceModel.Dispatcher.DispatchOperation dispatch)
{
DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior =
description.Behaviors.Find<DataContractSerializerOperationBehavior>();
dataContractSerializerOperationBehavior.DataContractResolver =
new ProxyDataContractResolver();
}
public void Validate(OperationDescription description)
{
// Do validation.
}
}
Then on your ServiceContract interfaces you add the DataAnnotation [ApplyDataContractResolver] right among your other annotations such as [OperationContract], above any method signature that returns an entity:
[OperationContract]
[ApplyDataContractResolver]
[FaultContract(typeof(AtcWcfEntryNotFoundException))]
Case GetSingleByCaseNumber(int number);

EF4 and UnitOfWork - How to make custom properties work

Say I have:
public class A
{
public virtual int Id { get; set; }
}
public class ARepository
{
private SomeContext _context;
public ARepository(IUnitOfWork unitOfWork)
{
_context = unitOfWork;
}
public A GetAById(int aId)
{
return _context.A.Where(o => o.Id == aId).SingleOrDefault();
}
}
public class B
{
public virtual int Id { get; set; }
public virtual Category Category { get ; set; } //enum with NEW and OLD values
public virtual int Quantity { get; set; }
}
public class BRepository
{
private SomeContext _context;
public BRepository(IUnitOfWork unitOfWork)
{
_context = unitOfWork;
}
public B GetBById(int bId)
{
return _context.B.Where(o => o.Id == bId).SingleOrDefault();
}
}
And I'm working with Entity Framework (4.1 code first).
How would I implement for example a custom property in A class like:
//returns the total of all B objects in the context where the category is NEW
public int NewBTotals
{
}
And not having to create a context?
Hopefully my question is clear enough, if not please let me know and I'll try to be more descriptive of what I want to achieve (ran out of time).
I found that even by B not having a foreign key to A, I can create a navigation property from A to B and vice versa which kind of solves the problem on its own.

EF 4.1 Mapping Inheritence on a Many-to-Many relationship

Confusing Situation
I have a situation where I have 2 entities where 1 inherits from the other, that need to map to 2 separate tables, but code use should be around the base of the 2 entities.
Details
public class Team
{
public virtual int Id { get; set; }
public virtual ICollection<Employee> Members { get; set; }
}
public class Employee
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
public class EmployeeInfo : Employee
{
public virtual int Id { get; set; }
public virtual decimal Amount { get; set; }
}
We have an existing database schema where Employee and EmployeeInfo are separate tables with a FK between EmployeeInfo_Id and Employee_Id.
In our system "managers" will be adding Employee's to the system, with a set of private information (more properties than listed above) like pay, and add them to a Team. Other areas of the system will be using the Team or Employee objects for various other things. We would like to have to code super simple if the mapping can be done.
When a manager creates a new employee we would like the code to look something like this:
public void Foo(string name, decimal pay)
{
// create the employee
var employee = new EmployeeInfo();
employee.Name = name;
employee.Pay = pay;
// add him/her to the team
_team.Employees.Add(employee); // the idea being that consumers of the Team entity would not get the separate employee info properties
// save the context
_context.SaveChanges();
}
The end result would be that the EmployeeInfo properties entered into the EmployeeInfo table and the base Employee data is entered into the Employee table and added to the Team via the association table TeamEmployees.
So far I'm trying the current mappings, and I get an invalid column named "Discriminator." When just adding an employee to a team.
public class TeamConfiguration : EntityTypeConfiguration<Team>
{
public TeamConfiguration()
{
ToTable("Team");
HasKey(t => t.Id);
HasMany(t => t.Members).WithMany(m => m.Teams)
.Map(m =>
{
m.MapLeftKey("Team_Id");
m.MapRightKey("Employee_Id");
m.ToTable("TeamEmployees");
});
}
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
ToTable("Employee");
ToTable("EmployeeInfo");
HasKey(t => t.Id);
Property(p => p.Name);
HasMany(m => m.Teams)
.WithMany(t => t.Members)
.Map(m =>
{
m.MapLeftKey("Employee_Id");
m.MapRightKey("Team_Id");
m.ToTable("TeamEmployees");
});
}
}
Also, if I take the many-to-many between team and employee out of the mix I get a FK exception on Employee_Id to EmployeeInfo_Id.
Thanks, JR.
Discriminator is a column that's being added to your table when you use Table Per Hierarchy approach.
I think what you're looking for is "Table per Type (TPT)". Decorate your EmployeeInfo class as follows:
[Table("EmployeeInfo")]
public class EmployeeInfo : Employee
Or add below to your OnModelCreating event:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Entity<EmployeeInfo>().ToTable("EmployeeInfo");
...
}
Or, create the following class and use it like modelBuilder.Configurations.Add(new EmployeeInfoConfiguration()); in OnModelCreating method:
public class EmployeeInfoConfiguration : EntityTypeConfiguration<EmployeeInfo>
{
public EmployeeInfoConfiguration()
{
ToTable("EmployeeInfo");
}
}
This will cause EF to create EmployeeInfo table with necessary constraints.
Also, it's good to initialize your collections in your objects' constructors to prevent null exception. For example in Team class:
public Team()
{
this.Employees = new HashSet<Employee>();
}
I copied your code exactly, and changed the following parts:
public class Team
{
public Team()
{
this.Members = new HashSet<Employee>();
}
public virtual int Id { get; set; }
public virtual ICollection<Employee> Members { get; set; }
}
public class Employee
{
public Employee()
{
this.Teams = new HashSet<Team>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
[Table("EmployeeInfo")]
public class EmployeeInfo : Employee
{
public virtual int Id { get; set; }
public virtual decimal Amount { get; set; }
}
In the DbContext, no changes:
public partial class TestEntities : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<EmployeeInfo> Employee_Info { get; set; }
public DbSet<Team> Teams { get; set; }
}
and your working Foo method:
public static void Foo(string name, decimal pay)
{
var _team = new Team();
var context = new TestEntities();
context.Teams.Add(_team);
// create the employee
var employee = new EmployeeInfo();
employee.Name = name;
employee.Amount = pay;
context.Employees.Add(employee);
context.SaveChanges();
// add him/her to the team
_team.Members.Add(employee);
// save the context
context.SaveChanges();
}
Finally, remove ToTable("EmployeeInfo"); part from EmployeeConfiguration since you have mentioned this correctly in your mode creating event.
For more info about Table Per Type approach, check out this great article.

in entity framework code first, how to use KeyAttribute on multiple columns

I'm creating a POCO model to use with entity framework code first CTP5. I'm using the decoration to make a property map to a PK column. But how can I define a PK on more then one column, and specifically, how can I control order of the columns in the index? Is it a result of the order of properties in the class?
Thanks!
NOTE:
As of 2019 this answer became non-valid for later EntityFramework versions.
You can specify the column order in the attributes, for instance:
public class MyEntity
{
[Key, Column(Order=0)]
public int MyFirstKeyProperty { get; set; }
[Key, Column(Order=1)]
public int MySecondKeyProperty { get; set; }
[Key, Column(Order=2)]
public string MyThirdKeyProperty { get; set; }
// other properties
}
If you are using the Find method of a DbSet you must take this order for the key parameters into account.
To complete the correct answer submitted by Slauma, you can use the HasKey method to specify an order for composite primary keys as well:
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
}
public class Ctp5Context : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasKey(u => new
{
u.UserId,
u.Username
});
}
}
If, like me, you prefer to use a configuration file you can do that in this way (based on Manavi's example):
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
}
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
ToTable("Users");
HasKey(x => new {x.UserId, x.Username});
}
}
Obviously you have to add the configuration file to your context:
public class Ctp5Context : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserConfiguration());
}
}
Use as a anonymous object:
modelBuilder.Entity<UserExamAttemptQuestion>().ToTable("Users").HasKey(o => new { o.UserId, o.Username });