Code First Foreign Key - entity-framework

I am new to entity framework. I have following models.
public partial class PropertyDetail
{
public int PropertyID { get; set; }
public string PropertyName { get; set; }
public virtual PropertyAddress PropertyAddress { get; set; }
public string AnalyticsView { get; set; }
public string MoreInformationLink { get; set; }
}
public class PropertyAddress
{
public string PropertyName { get; set; }
public string StreetAddress { get; set; }
public string PostalCode { get; set; }
public virtual PropertyDetail PropertyDetail { get; set; }
}
I want PropertyID from PropertyDetail to be primary key and PropertyName to be Foreign key in PropertyAddress table.
Thank for help.

with EF6 you can't: the FK must be of the same type as the PK. I heard about that in EF7 but not for sure.

Related

Multiple foreign key relationships in single entity

I need to configure multiple foreign key 1:1 relationships in single entity, I have gone through so many posts, Please check below code for your reference. Please help me to configure the same in entity framework.
public class Institution
{
public Institution()
{
InstitutionId = Guid.NewGuid().ToString("N");
}
public string InstitutionId { get; set; }
public string InstutionName { get; set; }
public string BackgroundImage { get; set; }
public string InstitutionCode { get; set; }
public int Logo { get; set; }
public string AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Address Address { get; set; }
public string ServerId { get; set; }
[ForeignKey("ServerId")]
public virtual Server InstitutionServer { get; set; }
}
Thanks in advance,

System.InvalidOperationException: The property 'Emp_Status' is part of the object's key information and cannot be modified

I have the following code:
Class
public partial class Emp_Details
{
public long Emp_ID { get; set; }
public string Emp_Title { get; set; }
public string Emp_Name { get; set; }
public string Emp_LastName { get; set; }
public string Emp_Status{ get; set; }
}
entity Code
using (LoginEntities dbcontext = new LoginEntities())
{
Emp_Details emp = dbcontext.Emp_Details.Single(i => i.Emp_ID == empid);
emp.Emp_Status = status;
dbcontext.SaveChanges();
}
I am getting the exception
System.InvalidOperationException: The property 'Emp_Status' is part of the object's key information and cannot be modified.
I have searched for a solution and found 2 possible fixes:
1)Set a primary Key. If there is no primary key on a table, it will simply select the non-nullable columns as a concatenated primary key and the entity will be read/only.
2) Use a direct update such as:
dbcontext.Database.ExecuteSqlCommand(
"UPDATE Emp_Details SET [Emp_Status] = {0} WHERE [Emp_ID] = {1}", status, empid);
Is there any way to do this update without having to touch the database, set primary keys, or mess with the class file?
Your entity doesn't have a primary key. So:
public partial class Emp_Details {
public long Id { get; set; } // pay attention to this
public string Emp_Title { get; set; }
public string Emp_Name { get; set; }
public string Emp_LastName { get; set; }
public string Emp_Status{ get; set; }
}
Or
public partial class Emp_Details {
public long Emp_DetailsId { get; set; } // pay attention to this
public string Emp_Title { get; set; }
public string Emp_Name { get; set; }
public string Emp_LastName { get; set; }
public string Emp_Status{ get; set; }
}
Or
public partial class Emp_Details {
[Key] // pay attention to this
public long Emp_ID { get; set; }
public string Emp_Title { get; set; }
public string Emp_Name { get; set; }
public string Emp_LastName { get; set; }
public string Emp_Status{ get; set; }
}
Each of above changes, will solve the problem.

EF code first model not in sync with database

My EF Code First model for some reason is not in sync with the db. I'm getting this error:
{"Invalid column name 'Type_Id1'."}
The field is actually called 'Type_Id' so I'm not sure from where that 1 comes up. I have the table column called as Type_Id and also I've added a Type_Id in my type entity model.
Why might I be getting that error message, plus why I'm getting 1 at the end of the name?
Update
My Task class:
public class Task
{
public Task()
{
Language = 1;
Grades = new HashSet<Grade>();
Categories = new HashSet<Category>();
Subjects = new HashSet<Subject>();
Rooms = new Collection<Room>();
Tools = new Collection<Tool>();
}
[Key]
public int Id { get; set; }
public string Description { get; set; }
public virtual TaskType Type { get; set; }
public string Rules { get; set; }
[Required]
[StringLength(200), MinLength(1)]
public string Name { get; set; }
public int PreperationTime { get; set; }
public int InstructionTime { get; set; }
public int TaskTime { get; set; }
public int Type_Id { get; set; }
public string VideoLink { get; set; }
[Required]
public int Language { get; set; }
public int? MinimumParticipants { get; set; }
public int? MaximumParticipants { get; set; }
public int? Rating { get; set; }
[Required]
public string CreatedBy { get; set; }
public virtual ICollection<Grade> Grades { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
public virtual ICollection<Tool> Tools { get; set; }
}
DBContext class:
public ApplicationDbContext() : base("DefaultConnection", false)
{
}
public DbSet<Task> Tasks { get; set; }
public DbSet<TaskType> TaskTypes { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
You need to add the FK attribute on your navigation property. EF is creating Type_Id1 because Type_Id already exists (although it can't tell by convention it is the FK).
[ForeignKey("Type_Id")]
public virtual TaskType Type { get; set; }
https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships

The relationship could not be changed because one or more of the foreign-key properties is non-nullable when updating

I have some problems when updating my model. This is my update code:
public void Update(Class #class)
{
var updatedClass = context.Classes.Where(c => c.ClassId == #class.ClassId).FirstOrDefault();
updatedClass.ClassPriceTypeId = #class.ClassPriceTypeId;
updatedClass.ClassType = #class.ClassType;
updatedClass.Name = #class.Name;
updatedClass.Title = #class.Title;
updatedClass.MetaTag = #class.MetaTag;
updatedClass.MetaDescription = #class.MetaDescription;
updatedClass.UrlSafe = #class.UrlSafe;
updatedClass.Header = #class.Header;
updatedClass.Margin = #class.Margin;
updatedClass.ImageName = #class.ImageName;
updatedClass.GroupId = #class.GroupId;
updatedClass.IsPublished = #class.IsPublished;
context.SaveChanges();
}
First problem is that I have made LazyLoadingEnabled=false but after fetching updatedClass the relational properties like Group is not null.
Second problem is that in some of #class objects I can easily update my entity but in some others I see this error:
The operation failed: The relationship could not be changed because
one or more of the foreign-key properties is non-nullable. When a
change is made to a relationship, the related foreign-key property is
set to a null value. If the foreign-key does not support null values,
a new relationship must be defined, the foreign-key property must be
assigned another non-null value, or the unrelated object must be
deleted.
Update
This is Class model:
public class Class
{
public int ClassId { get; set; }
public int GroupId { get; set; }
public int ClassPriceTypeId { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string MetaTag { get; set; }
public string MetaDescription { get; set; }
public string UrlSafe { get; set; }
public string Header { get; set; }
public string ImageName { get; set; }
public int Margin { get; set; }
public string ClassType { get; set; }
public bool IsPublished { get; set; }
public virtual Group Group { get; set; }
public virtual List<Product> Products { get; set; }
public virtual List<Comparing.Model.Price.Price > Prices { get; set; }
public virtual ClassPriceType.ClassPriceType ClassPriceType { get; set; }
public virtual List<Garanty> Garanties { get; set; }
public virtual List<PhoneModel> PhoneModels { get; set; }
public virtual List<ClassPartner> ClassPartners { get; set; }
public virtual List<Content> Contents { get; set; }
}
And this is Group model:
public class Group
{
public int GroupId { get; set; }
public int SectionId { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string MetaTag { get; set; }
public string MetaDescription { get; set; }
public string UrlSafe { get; set; }
public string Header { get; set; }
public string ImageName { get; set; }
public bool IsPublished { get; set; }
public virtual Section Section { get; set; }
public virtual List<Class> Classes { get; set; }
}
Can anyone help me about the problem?
I guess, you are trying to update a primary key field which is having a relation ship with other foreign key with not null constraint. I guess you need to use update cascade.

How to use CodeFirst (EntityFramework, Microsoft) to make nullable complex column

I've got a definition like below and essentially, I want to create this in the EmailAccount class:
public EmailUser? EmailUserAccountInfo {get;set;}
the compiler gives me an error about non-nullable types. My goal is I want to make the EmailUser optional. I'm kind of confused because I can set EmailUserAccountInfo = null directly.
var r = new EmailAccount()
{
EmailUserAccountInfo = null,
Id = 1001
};
public class EmailAccount
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public EmailUser EmailUserAccountInfo { get; set; }
}
public class EmailUser
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public EmailAccount EmailAcount { get; set; }
public string EmailAddress { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Temperature { get; set; }
public string WeatherString { get; set; }
public ImageDetail ImageOfUser { get; set; }
}
You can do this if you add a foreign key and you mark that nullable:
public class EmailAccount
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
// Foreign key
public int? EmailUserAccountInfoId { get; set; }
// Navigation property
public virtual EmailUser EmailUserAccountInfo { get; set; }
}
See this document about naming conventions for Code-First. (Scroll down to Relationship Convention)