Entity Framework multiple parent tables - asp.net-mvc-3

I have an existing database that I am trying to access via Entity Framework 4.3. Most tables and relationships haven't been a problem, but this set of tables is causing me a few issues which I can't seem to find an answer to.
Here are the (condensed) entities:
Customer
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
private int addressSourceTypeID = 2;
[NotMapped]
public int AddressSourceTypeID {
get { return addressSourceTypeID; }
set { addressSourceTypeID = value; } }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Contract> Contracts { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
Contract
public class Contract
{
public int ContractID { get; set; }
public string Name { get; set; }
private int addressSourceTypeID = 4;
[NotMapped]
public int AddressSourceTypeID {
get { return addressSourceTypeID; }
set { addressSourceTypeID = value; } }
public virtual int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
//public virtual ICollection<Address> Addresses { get; set; }
}
Address
public class Address
{
[Key]
public int AddressID { get; set; }
public int AddressSourceTypeID { get; set; }
[ForeignKey("Customer")]
public int SourceKey { get; set; }
public virtual Customer Customer { get; set; }
//public virtual Contract Contract { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
What I have above is two entities Customer and Contract that both can have child Address entities. Currently the Address entity is set up to be a child of the Customer entity and this works fine as there isn't a link to Contract from Address.
I have tried adding in Contract to the Address entity as I have done with the Customer entity as you can see from the commented out code segments. Unfortunatly this doesn't work, but I'm not surprised due to the reference to Customer in the Address ForeignKey annotation. I even tried to create specific version of the Address entity (i.e. CustomerAddress), but I get an error when more than one entity is attempting to bind to the same table.
I have also tried using ModelBuilder in the EF DBContext however my knowledge here is pretty limited and I'm not sure how to do it in this case.
Overall, what I need is the following:
Customer entity to have a collection of child Addresses.
Contract entity to have a collection of child Addresses.
The link between these 'parent' tables to the Address table uses the following:
Customer: CustomerID => Address: SourceKey AND Customer: AddressSourceTypeID (always 2) => Address: AddressSourceTypeID.
Contract: ContractID => Address: SourceKey AND Contract: AddressSourceTypeID (always 4) => Address: AddressSourceTypeID.
If anyone could help me or point me in the correct direction that would be great.
Thanks very much.

You can either have EF enforce your SourceKey attribute using Table per Hierarchy Inheritance - and then you're mapping will break, or you can enforce the SourceKey in your business logic and only have EF manage the main Address class.
If you have to maintain your current DB schema, I think having your business logic enforce your SourceKey as a disriminator is your only option:
public class Address
{
public int AddressID { get; set; }
public int AddressSourceTypeID { get; set; }
public int SourceKey { get; set; }
public virtual Contract Contract { get; set; }
public virtual Customer Customer { get; set; }
}
public class Contract
{
public Contract()
{
this.Addresses = new List<Address>();
}
public int ContractID { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Customer
{
public Customer()
{
this.Addresses = new List<Address>();
}
public int CustomerID { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
And this in your fluent mappings:
modelBuilder.Entity<Address>().HasOptional(t => t.Contract)
.WithMany(t => t.Addresses)
.HasForeignKey(d => d.SourceKey);
modelBuilder.Entity<Address>().HasOptional(t => t.Customer)
.WithMany(t => t.Addresses)
.HasForeignKey(d => d.SourceKey);
Alternatively - if you created a CustomerAddress and ContractAddress, you can using TPH inheritance enforce the SourceKey - but currently there's no way to map the Nav properties:
public abstract class Address
{
[Key]
public int AddressID { get; set; }
public int AddressSourceTypeID { get; set; }
public int SourceKey { get; set; }
}
public class CustomerAddress : Address
{
public virtual Customer Customer { get; set; }
}
public class ContractAddress : Address
{
public virtual Contract Contract { get; set; }
}
And this as your mapping:
modelBuilder.Entity<Address>()
.Map<ContractAddress>(m => m.Requires("AddressSourceTypeID").HasValue(2))
.Map<CustomerAddress>(m => m.Requires("AddressSourceTypeID").HasValue(4));
This will enforce AddressSourceTypeID as your discriminator - unfortunately the breakdown here is in mapping your nav property back to the ContractAddress and Customer Address. See this related post which had the same basic problem. Maybe this will start you in the right direction at least.

Related

ASP.NET Model Relationship

I'm currently learning ASP.NET MVC and Web API.
I'm trying to create a User Model. Users can have any number of UserContacts. UserContacts reference the User it is a contact of and the User who is the contact. I have made a model called UserContact because attached to this Model is additional information.
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class UserContact
{
public int UserContactID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID"), Column(Order = 0)]
[Required]
public User User { get; set; }
public int ContactID { get; set; }
[ForeignKey("ContactID"), Column(Order = 1)]
[Required]
public User Contact { get; set; }
public DateTime ContactSince { get; set; }
}
So this gives me an error referring to cascading Delete. How do I set up a relationship like this where two foreign keys point to the same Model type? I have yet to grasp Entity Framework syntax as well. If I don't have an ICollection of UserContacts in the User model, does this hinder my ability to grab the UserContacts associated with that User?
When you have a foreign key and the foreign key columns are not nullable(means,required). EF will automatically tries to enable cascading delete on the relationsip. In your case, it will try to enable Cascading delete for both the foreign key columns and both of them points to the same user table! That is the reason you are getting this error. What if you have a UserContact record with Both UserId and ContactID points to the same User record. Cascading delete is confused now :)
Also, since one user can have more than one Contacts, We need a Contacts property on the User table to represent that. This will be a collection of UserContact's. Also this user can be a a contact of many other people. So Let's create another property for that.
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<UserContact> Contacts { set; get; }
public ICollection<UserContact> ContactOf { set; get; }
}
public class UserContact
{
public int UserContactID { get; set; }
public int UserID { get; set; }
public User User { get; set; }
public int ContactID { get; set; }
public User Contact { get; set; }
public DateTime ContactSince { get; set; }
}
And in your DbContext class, We can configure the foreign key relation ships and tell EF to disable cascade delete using fluent configuration inside the overridden OnModelCreating method. The below code will disable cascading delete on both the the relationships. But for your error to go away. disabling on one foreign key is enough.
public class YourDbContext: DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserContact>()
.HasRequired<User>(g=>g.User)
.WithMany(g=>g.Contacts)
.HasForeignKey(g=>g.UserID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<UserContact>()
.HasRequired<User>(g => g.Contact)
.WithMany(g => g.ContactOf)
.HasForeignKey(g => g.ContactID)
.WillCascadeOnDelete(false); // this one is not really needed to fix the error
base.OnModelCreating(modelBuilder);
}
public DbSet<User> Users { set; get; }
public DbSet<UserContact> UserContacts { set; get; }
}
This will create the tables like you wanted with the necessary foreign keys.
There is not enough information for EF to figure out the relationships on the other side, so yes, you need collections. You can use the InverseProperty annotation to clarify (or fluent api statements):
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[InverseProperty("User")]
public Virtual ICollection<UserContact> Users{ get; set; }
[InverseProperty("Contact")]
public Virtual ICollection<UserContact> Contacts { get; set; }
}
public class UserContact
{
public int UserContactID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID"), Column(Order = 0)]
[Required]
public User User { get; set; }
public int ContactID { get; set; }
[ForeignKey("ContactID"), Column(Order = 1)]
[Required]
public User Contact { get; set; }
public DateTime ContactSince { get; set; }
}
http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx

how to filter nested list using Linq lambda

I have a class person which has a list of addresses and phones as the follow code.
In my query I want a list of person but not including the address and phone that are already deleted, but is always returning all addresses and phones even they flag as deleted. How could I filter those nested lists using lambda?
public class Person{
public int PersonId { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<Phone> Phones{ get; set; }
public virtual Company Company { get; set; }
}
public class Address{
public int AddressId { get; set; }
public string Street { get; set; }
public bool Deleted { get; set; }
[ScriptIgnore]
public virtual Person Person { get; set; }
}
public class Phone{
public int PhoneId { get; set; }
public string Number{ get; set; }
public bool Deleted { get; set; }
[ScriptIgnore]
public virtual Person Person { get; set; }
}
return GetDbSet<Person>()
.Include("Address")
.Include("Phones")
.Where(i => i.Company.CompanyId == company.CompanyId)
.OrderByDescending(o => o.CreateTime).ToList();
Just add conditions in your Where clause to exclude deleted address and phone like:
Where(i => i.Company.CompanyId == company.CompanyId &&
i.Address.Any(r=> !r.Deleted) &&
i.Phone.Any(r=> !r.Deleted))

Data Annotation for foreign key relationship

I have two classes
public class Project
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int ManagerID { get; set; }
public int CoordID { get; set; }
[ForeignKey("ManagerID")]
public virtual Employee Manager { get; set; }
[ForeignKey("CoordID")]
public virtual Employee Coord { get; set; }
}
public class Employee
{
[Key]
public int EmpID { get; set; }
public string Name { get; set; }
[InverseProperty("ManagerID")]
public virtual ICollection<Project> ManagerProjects { get; set; }
[InverseProperty("CoordID")]
public virtual ICollection<Project> CoordProjects { get; set; }
}
The ManagerID and CoordID map to the EmpID column of the Employee table.
I keep getting an error for Invalid Columns becauce EF is not able to map correctly. I think it is looking for wrong column.
I think InverseProperty is used to refer to the related navigation property, not the foreign key, e.g.
public class Employee
{
[Key]
public int EmpID { get; set; }
public int Name { get; set; }
[InverseProperty("Manager")]
public virtual ICollection<Project> ManagerProjects { get; set; }
[InverseProperty("Coord")]
public virtual ICollection<Project> CoordProjects { get; set; }
}
Also, is there a reason why your names are ints and not strings?
Best guess would be to use fluent API in your context via OnModelCreating. By renaming the column, EF can't figure out the original object to map so it's confused. However, Fluent API allows you to manually specify the map using something like the following:
public class MyContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Project> Projects { get; set; }
protected override OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>()
.HasRequired(x => x.Manager)
.WithMany(x => x.ManagerProjects)
.HasForeignKey(x => x.ManagerID);
modelBuilder.Entity<Project>()
.HasRequired(x => x.Coord)
.WithMany(x => x.CoordProjects)
.HasForeignKey(x => x.CoordID);
}
}

Entity Framework POCO Relationships

I am trying to implement code-first approach of entity framework. I have four entities UserInfo, Client, Admin and Account. I want relationships as:
Each Client has a UserInfo
Each Admin has a `UserInfo
Each Account is linked with a User(UserInfo)
Assuming these things i wrote the POCO models. With the relationships i want, is it correct ?Am i missing something?
public class UserInfo
{
public int UserInfoID { get; set; }
public Name Name { get; set; }
public Address Address { get; set; }
public Contact Contact { get; set; }
}
public class Admin
{
public int AdminID { get; set; }
public int UserInfoID { get; set; }
[ForeignKey("UserInfoID")]
public virtual UserInfo UserInfo { get; set; }
}
public class Client
{
public int ClientID { get; set; }
public CompanyDetails CompanyDetails { get; set; }
public int UserInfoID { get; set; }
[ForeignKey("UserInfoID")]
public virtual UserInfo UserInfo { get; set; }
}
public class Account
{
public int AccountID { get; set; }
[Required, Column("Balance"), Display(Name = "Account Balance")]
public double Balance { get; set; }
public int UserInfoID { get; set; }
[ForeignKey("UserInfoID")]
public virtual UserInfo UserInfo { get; set; }
}
What you have appears to be correct based on your requirements however I personally prefer the Entity Framework Model Builder when configuring your entities with Code First.
Using the model builder means that you don't have any attributes on your POCO entities which in turn means that you don't need an EF reference to use the entities.
Take a look at my article here for some more info on how to use the modelbuilder : http://blog.staticvoid.co.nz/2012/07/entity-framework-navigation-property.html

EF 4.1 Code First multiple Many-to-Many relationships

I'm having trouble wrapping my head around a certain code-first relationship. I have three entities: Group, User, GroupPermission. The GroupPermission entity holds information about permissions that relate to a group. There are three permissions: leader, editor, user. The GroupPermission table should include the primary key Id and the name of the permission. Then I want a relationship table that looks something like this: Id - Group_Id - User_Username - GroupPermission_Id. There can be multiple groups, multiple users, multiple permissions. I have plenty of examples that help me make a single relationship table, but I can't find anything that includes multiple relationships.
Here are my entities...
User:
public class User
{
[Key, StringLength(EntityLength.UsernameLength)]
public string Username { get; set; }
[Required, StringLength(EntityLength.NameLength)]
public string FirstName { get; set; }
[Required, StringLength(EntityLength.NameLength)]
public string LastName { get; set; }
[Required, StringLength(EntityLength.Email)]
public string Email { get; set; }
public bool Active { get; set; }
public DateTime DateCreated { get; set; }
public virtual UserPermission UserPermission { get; set; }
public virtual ICollection<Group> Groups { get; set; }
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
public virtual ICollection<GroupPermission> GroupPermissions { get; set; }
public string FullName
{
get { return FirstName + ' ' + LastName; }
}
}
Group:
public class Group
{
[Key]
public int Id { get; set; }
[Required, StringLength(EntityLength.GenericLength)]
public string Name { get; set; }
[Required, StringLength(EntityLength.DescriptionLength)]
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<GroupPermission> GroupPermissions { get; set; }
}
GroupPermission:
public class GroupPermission
{
[Key]
public int Id { get; set; }
[StringLength(EntityLength.GenericLength)]
public string Name { get; set; }
public int GroupId { get; set; }
public virtual ICollection<Group> Groups { get; set; }
public int UserId { get; set; }
public virtual ICollection<User> Users { get; set; }
public enum Permission
{
Leader = 1,
Editor = 2,
User = 3
}
}
When the tables are created using this structure, I get a GroupPermissions table that has Id, Name, GroupId, and UserId. This table needs to only be Id and Name. Then it creates a GroupPermissionUsers table that holds GroupPermissions_Id and User_Username. This is the table that should be Id, Group_Id, User_Username, GroupPermission_Id.
Does anybody have any tips to accomplish this or am I thinking about the design of this incorrectly?
In such case you are missing additional entity. It should look like:
New Permission entity with Id and Name:
public class Permission
{
[Key]
public int Id { get; set; }
[StringLength(EntityLength.GenericLength)]
public string Name { get; set; }
public virtual ICollection<GroupPermission> GroupPermissions { get; set; }
}
Modified GroupPermission entity to form junction table among Users, Groups and Permissions:
public class GroupPermission
{
[Key]
public int Id { get; set; }
public int GroupId { get; set; }
public virtual Group Group { get; set; }
public string UserName { get; set; }
[ForeignKey("UserName")]
public virtual User User { get; set; }
public int PermissionId { get; set; }
public virtual Permission Permission { get; set; }
}

Resources