Model:
public class Address
{
[Key]
public long AddressId { get; set; }
public string Street { get; set; }
public string Town { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class User
{
[Key]
public long UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public virtual List<Address> Addresses { get; set; }
}
DBContext:
public class DataModelContext : DbContext
{
public DbSet<Address> Addresses { get; set; }
public DbSet<User> Users{ get; set; }
}
Using above code its creating this schema for DB.
Addresses Users
----------- -------
AddressId(PK) UserId(PK)
Street UserName
Town Password
State
Country
User_UserId(FK)
Now i want to access User_UserId from Addresses table, but it not showing any property there. Its giving error "Address does not contain a definition for User_UserId.....
using (var db = new DataModelContext())
{
db.Addresses.Select(x=>x.User_UserId).ToList();
}
Use Foreign-Key Association instead of independant association while creating models. It means that, you must include a foreign key property in your model alongside with a corresponding Navigational Property. For example:
public class Address
{
...
public int UserId {get; set;} //Foreign-Key property
[ForeignKey("UserId")]
public virtual User User { get; set; } // Navigational Property
...
}
Read this article for more information.
Related
I have Employee, Address and Organization classes. below are the details
public partial class Employees
{
public Employees()
{
AddressDetails = new HashSet<AddressDetails>();
OrganizationDetails = new HashSet<OrganizationDetails>();
}
public string Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public ICollection<AddressDetails> AddressDetails { get; set; }
public ICollection<OrganizationDetails> OrganizationDetails { get; set; }
}
public partial class AddressDetails
{
public int Id { get; set; }
public string Address { get; set; }
public string Type { get; set; }
public string EmployeeId { get; set; }
public Employees Employee { get; set; }
}
public partial class OrganizationDetails
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public string EmployeeId { get; set; }
public Employees Employee { get; set; }
}
I have used fully defined relationship, you can see Employee has collections of both AddressDetails and OrganizationDetails as navigation properties. And each of them have EmployeeId and Employee in the same way.
My problem is, when i try to fetch Employee details using Include(), both AddressDetails and OrganizationDetails are loaded that's fine, but when i checked both the collections each entity has again loaded Employee information and so on.
for example: if i check AddressDetails collection which is loaded, Address object has information of Employee and again that Employee has collections of both AddressDetails and OrganizationDetails.
Please help me how can i avoid this. I don't want to remove Employee object property from AddressDetails and OrganizationDetails. is there anyway to make it work with Include().
here is the query i'm using to load these navigation properties.
List employees = _context.Employees.Include(emp => emp.AddressDetails).Include(emp => emp.OrganizationDetails).ToList();
I am using EF 6.1.1.
I am unable to figure out how to create One-to-One relationship between two classes/tables with both entities have their owns PKs. I originally posted question link but could not get much help on it OR i am not able to get it. So, here i am putting my question in simple way.
Appreciate if someone can share thoughts on it.
My Requirement:
I would like create One-To-One relationship between Principle and Dependant with 'Id' from Principle class acts as Foreign Key in dependant class.
Principle Class
public class Student
{
public string FullName {get; set;}
}
Dependant Class
public class StudentReport
{
public string RollNumber { get; set; }
public string StudentType { get; set; }
}
Add PKs – EF requires this:
public class Student
{
public int Id { get; set; }
public string FullName { get; set; }
}
public class StudentReport
{
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
}
Note that EF 5 and later supports naming conventions: Id indicates a primary key. Alternately, it also supports the name of the class followed by "Id", so the above keys could have been StudentId for Student and StudentReportId for StudentReport, if you wished.
Add the foreign relation as a navigation property to at least one of the tables – in this case, you stated that StudentReport is the dependent, so let's add it to that one:
public class Student
{
public int Id { get; set; }
public string FullName { get; set; }
}
public class StudentReport
{
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public Student Student { get; set; }
}
Again – by naming convention – EF determines that a single Student property on StudentReport indicates that this is a navigational property associated with a foreign key. (By defining only the Student property, but no foreign key property, you are indicating that you don't care what EF names the associated FK ... basically, you're indicating you'll always access the related Student via the property.)
If you did care about the name of the FK property, you could add it:
public class Student
{
public int Id { get; set; }
public string FullName { get; set; }
}
public class StudentReport
{
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
}
Again – by naming convention – EF determines that StudentId is the FK associated with the Student property because it has the class name, "Student", followed by "Id".
All of this, so far, has been using conventions as defined in Entity Framework Code First Conventions, but Data Annotations are also an option, if you wish:
public class Student
{
[Key]
public int Id { get; set; }
public string FullName { get; set; }
}
public class StudentReport
{
[Key]
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
[ForeignKey("Student")]
public int StudentId { get; set; }
public Student Student { get; set; }
}
Doing this is actually a good idea, because it makes clearer your intent to other programmers that might not be aware of EF Conventions – but can easily infer them from simply looking at EF Data Annotations – and is still less cumbersome than Fluent API.
UPDATE
I just realized, I left this as a one-to-many, with enforcement of the one-to-one relationship being left to do in the code using this model. To enforce the one-to-one in the model, you could add a navigation property to the Student class going the other way:
public class Student
{
public int Id { get; set; }
public string FullName { get; set; }
public StudentReport StudentReport { get; set; }
}
public class StudentReport
{
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public Student Student { get; set; }
}
However, that's going to break, because EF doesn't know which entity to insert first on an add. To indicate which is dependent, you have to specific that the dependent class' PK is the FK to the principal class (this enforces one-to-one because – in order for a Student/StudentReport pair to be associated – their Id properties must be the exact same value):
public class Student
{
public int Id { get; set; }
public string FullName { get; set; }
public StudentReport StudentReport { get; set; }
}
public class StudentReport
{
[ForeignKey("Student")]
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public Student Student { get; set; }
}
or, using the full set of Data Annotations from earlier:
public class Student
{
[Key]
public int Id { get; set; }
public string FullName { get; set; }
public StudentReport StudentReport { get; set; }
}
public class StudentReport
{
[Key, ForeignKey("Student")]
public int Id { get; set; }
public string RollNumber { get; set; }
public string StudentType { get; set; }
public Student Student { get; set; }
}
(source: mcainsh.info)
The tables are just for an example, what I am trying to do is map a virtual Manufacturer in the Book entity. I've tried using data annotation similar to below:
[ForeignKey("PublisherId")]
public virtual Publisher { get; set; }
[ForeignKey("Publisher.ManufacturerCompanyId")]
[InverseProperty("ManufacturerId")]
public virtual Manufacturer { get; set; }
Is this something that can be done?
You're configuring incorrectly the foreign keys. To do what you want, your model should be like this:
public class Book
{
public int Id { get; set; }
public string Title{ get; set; }
public int PublisherId { get; set; }
[ForeignKey("PublisherId")]
public virtual Publisher Publisher{ get; set; }
public int ManufacturerId { get; set; }
[ForeignKey("ManufacturerId")]
public virtual Manufacturer Manufacturer { get; set; }
}
public class Manufacturer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Publisher
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
In this model you have two one-to-many relationships, the first between Book and Publisher and the second one between Book and Manufacturer. As you can see in the Book class, if you want to use a FK property you must declare a property of the same type of the PK of the related entity (see PublisherId and ManufacturerId).Now, you can apply the ForeignKey annotation to the navigation property and tell it which property is the foreign key for the relationship, as I show above. Alternatively, you can addForeignKey attribute to the ManufacturerId, along with information telling it which navigation property represents the relationship it is a foreign key for:
[ForeignKey("Manufacturer")]
public int ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
If you want, you don't need to create the FKs properties, EF will do the job for you begin the escene. It will create a FK row in your Books table for each relationship (check the DB after execute your code):
public class Book
{
public int Id { get; set; }
public string Title{ get; set; }
//public int PublisherId { get; set; }
//[ForeignKey("PublisherId")]
public virtual Publisher Publisher{ get; set; }
//public int ManufacturerId { get; set; }
//[ForeignKey("ManufacturerId")]
public virtual Manufacturer Manufacturer { get; set; }
}
I am issuing a very strange scenario using Code first with existing database and asp.net identity entity framework. I have a simple userprofile model
[Table("CSUserProfile")]
public partial class UserProfile
{
[Key]
public string Id { get; set; }
[Required]
[Display(Name = "FirstName")]
public string FirstName { get; set; }
[Required]
[Display(Name = "LastName")]
public string LastName { get; set; }
[Required]
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required]
public string Email { get; set; }
[Required]
[Display(Name = "Location")]
public string Location { get; set; }
[Required]
[Display(Name = "HomeTown")]
public string Hometown { get; set; }
public byte[] BlobData { get; set; }
[ForeignKey("fPersonLinkGID")]
public virtual List<ProfilePic> ProfilePic { get; set; }
}
and an image profile pic
[Table("CSProfilePic")]
public partial class ProfilePic
{
[Key]
public Guid? GID { get; set; }
public string fPersonLinkGID { get; set; }
public byte[] BlobData { get; set; }
}
the foreign key is the fPersonLinkGID. everything works fine but my problem is that if i want an one-to-one relation between the userprofile and the image like this
public virtual ProfilePic ProfilePic { get; set; }
(which is the correct scenario) I am getting this strange exception :
The ForeignKeyAttribute on property 'ProfilePic' on type 'eUni.Model.Application.UserProfile' is not valid. The foreign key name 'fPersonLinkGID' was not found on the dependent type 'eUni.Model.Application.UserProfile'. The Name value should be a comma separated list of foreign key property names.
I can not understand why I am getting that exception
You could read this answer. It introduces how to configure one to one relationship by HasRequired and WithOptional.
As for me, I will create one to one relationship by following way.
public class Store {
[Key]
public long Id { get; set; }
public virtual Item TheItem { get; set; }
// ....
}
public class Item {
// It is FK, and also PK.
[Key, ForeignKey("TheStore")]
public long Id { get; set; }
// The same string in the ForeignKey attribute. Ex: ForeignKey("TheStore")
public virtual Store TheStore { get; set; }
// ....
}
I am using EF 4.4 + Code First.
I was trying to add a ChartofAccount entity to DBContext with the Company's key filled, but it ask me to fill the Company's CompanyName as well at validation. I thought DBContext will look up the associate Company for me, instead of trying to add a new Company?
public class ChartofAccount: MasterData
{
public ChartofAccount()
{
Company = new Company();
Category1 = new AccountCatagory();
Category2 = new AccountCatagory();
}
[Key]
[Required]
public string Code { get; set; }
public virtual Company Company { get; set; }
[Required]
public string AccountName { get; set; }
[Required]
[StringLength(3)]
public string AccountCurrency { get; set; }
public virtual AccountCatagory Category1 { get; set; }
public virtual AccountCatagory Category2 { get; set; }
public string Reference { get; set; }
public bool HasTransaction { get; set; }
}
public class Company : MasterData
{
[Key]
public int Id { get; set; }
[Required]
public string CompanyName { get; set; }
[Required]
DateTime CurrentAccountPeriod { get; set; }
[Required]
[StringLength(3)]
public string BaseCurrencyCode { get; set; }
}
Sadly, just the primary key of a related entity isn't enough. You need to round trip to the database to obtain the entity in the same data context.
Example:
var Company = db.Company.Single(d => d.ID == id);
ChartofAccountToAdd.Company = Company;
db.ChartofAccount.Add(ChartofAccountToAdd);
db.SubmitChanges();
That will create the relationship with an already existing company.
EDIT:
I completely forgot about this when I answered. Edit your ChartOfAccount model to contain the foreign key for the Company like:
public class ChartofAccount: MasterData
{
{rest of your model}
public int CompanyID { get; set; }
}
and then set the foreign key to that new int property. Entity Framework will create the relationship without any issues. Don't set anything to the Company property on the model.