Saving Data using Entity Framework Code First - asp.net-mvc-4

I am using ASP.NET MVC Razor Entity Framework Code First C#
Class - A
public class Om_Category
{
[Key]
public int CategoryID { get; set; }
public String CategoryName { get; set; }
public String CategorySanitized { get; set; }
public Boolean IsActive { get; set; }
public DateTime CreationDate { get; set; }
}
Class - B
public class Om_CategorySkills
{
[Key]
public Int32 SkillID { get; set; }
public String Skill { get; set; }
public String SkillSanitized { get; set; }
public DateTime CreationDate { get; set; }
public Boolean IsActive { get; set; }
public Om_Category Category { get; set; }
}
When I try to create the record for table Om_CategorySkills. It says
cannot save the duplicate value in Om_Category table.
This is happening because I am sending the Om_Category class object in Om_CategorySkills class object because there are some fields in Om_Category class that are mandatory.
So I am passing the Om_Category class object also in Om_CategorySkills class object. Is there any way to fix this issue ?

Your navigation properties doesn't seem to be right.. Can you try (I didn't test),
public class Om_Category
{
[Key]
public int CategoryID { get; set; }
public String CategoryName { get; set; }
public String CategorySanitized { get; set; }
public Boolean IsActive { get; set; }
public DateTime CreationDate { get; set; }
public virtual Om_CategorySkills CategorySkills{ get; set; }
}
public class Om_CategorySkills
{
[Key]
public Int32 SkillID { get; set; }
public String Skill { get; set; }
public String SkillSanitized { get; set; }
public DateTime CreationDate { get; set; }
public Boolean IsActive { get; set; }
public int CategoryID {get;set;}
public virtual Om_Category Category { get; set; }
}

I see that your Om_CategorySkills object is lacking an Int32 Om_CategoryId property to be used as foreign key. I would also add a virtual modifier to the navigation property Category, in order to allow for lazy loading.
I think that it may be the case that the category object in your new/edited skill is already in the database, but was not the one retrieved by the context, so the context believes you are trying to save a new category with the Id of an existing one.
You should not try to save a skill object with a category object with no changes. Otherwise, the category object should be the one attached to the context.

Related

Should I inject another context into SaveChangesInterceptor?

I want to perform auditing, by logging entity changes. I have an Audit class:
public class Audit
{
public int Id { get; set; }
public string UserId { get; set; }
public string Type { get; set; }
public string TableName { get; set; }
public DateTime DateTime { get; set; }
public string OldValues { get; set; }
public string NewValues { get; set; }
public string AffectedColumns { get; set; }
public string PrimaryKey { get; set; }
}
I've created AuditingInterceptor which I will add to multiple contexts. The Audits table is not accessible through these contexts.
internal class AuditingInterceptor : SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync...
}
In order to save to the Audits table should I inject AuditContext that has access to Audits table or should I use another aproach?

Object reference not set to an instance of an object in .net core

I have two model class as;
public class MessageDetailModel
{
[Key]
public int messageDetailsId { get; set; }
public MessageModel messageModel { get; set; }
public string detail { get; set; }
public int senderId { get; set; }
public int customerId { get; set; }
public string phone { get; set; }
public DateTime date { get; set; }
}
and
public class MessageModel
{
[Key]
public int messageId { get; set; }
public int senderId { get; set; }
public int customId { get; set; }
public bool ReadInfo { get; set; }
public virtual List<MessageDetailModel> MessageDetails { get; set; }
}
and it is my context class ;
public virtual DbSet<MessageDetailModel> messageDetails { get; set; }
public virtual DbSet<MessageModel> messages { get; set; }
public virtual DbSet<PersonModel> persons { get; set; }
public virtual DbSet<DirectoryModel> directory { get; set; }
I am trying to get messageId over MessageDetailModel but messageId returns as 0 and I have that error "Object reference not set to an instance of an object"
Console.WriteLine(k.messageModel.messageId); //( k is my var which gets from messagedetail model)
How can ı reach messageId over MessadeDetailModel
There is no current link between your two models that would represent a Foreign Key.
You'd need to do something like this for your model if you want a Foreign Key to link to the related object:
public class MessageDetailModel
{
[Key]
public int messageDetailsId { get; set; }
[ForeignKey("messageId")] // Added Data Annotation for the Foreign Key relationship
public MessageModel messageModel { get; set; }
public string detail { get; set; }
public int senderId { get; set; }
public int customerId { get; set; }
public string phone { get; set; }
public DateTime date { get; set; }
public int messageId { get; set; } // This would be your Foreign Key
}
I've added the messageId column to your MessageDetailModel to match the Primary Key column of your MessageModel as that's necessary for the link to form.
You would use the [ForeignKey("messageId")] Data Annotation above the variable for the MessageModel to determine what value it needs to use when finding the object you want.

Is it possible to create a Domain Class which has Multiple FK Columns to same PK?

I'm a newbie to designing database.
I have problem how to define a domain class which has multiple foreign keys linked with a same primary key.
Here is my model:
namespace OceanFmsSystem.Domain
{
public class ExportTemplate
{
public int Id { get; set; }
public List<ExportBooking> ExportBookings { get; set; }
public string TemplateName { get; set; }
public int CustomerId { get; set; }
public string Incoterms { get; set; }
public string IncotermsDetail { get; set; }
public string PaymentTerm{ get; set; }
public int CountryOriginId { get; set; }
public int CountryDestinationId { get; set; }
}
}
What I want to do is that CountryOriginId & CountryDestinationId should refer to the below class as foreign keys:
namespace OceanFmsSystem.Domain
{
public class Country
{
public int Id { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
}
}
As far as I know, in EF Core there is an convention which I should name a foreign key as below for migration from code to database.
public type ClassNameOfPrimaryKeyId { get; set;}
Is there any possible way to make this happens?
Yes, possible. Your class should look like this:
public class ExportTemplate
{
//...
public int CountryOriginId { get; set; }
public Country CountryOrigin { get; set; }
public int CountryDestinationId { get; set; }
public Country CountryDestination { get; set; }
}
EF is smart enough to figure the Ids by convention. If you do not wish to follow the convention you can use [ForeignKey] attribute on the properties to configure the FK:
[ForeignKey("Origin")]
public int MyOriginId { get; set; }
public Country Origin { get; set; }

How to create a history model of a specific model on MVC 4

I'm still new in creating Models using Entity Framework and MVC 4 Razor. I'm having a problem on how can I save a history of a model. How can I create a model that have a history on specific tables or fields ? For ex: If I wish to create a history on the changes on the school. Its still not clear to me how will I I create the model that saves history. How will be the triggering do I have to execute the save function on different models with the same data ?
Thank you so much in advance.
If anyone could be a simple example of model and a model history and how it is functioning, I'll be very grateful. Like a Sales or sales history.
Here's my code
One To Many
public class Child
{
[Key]
public int ChildID { get; set; }
[Required,Display(Name="Project Code")]
public string ProjectCode { get; set; }
public string Status { get; set; }
[DataType(DataType.Date)]
public DateTime StatusDate { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }
public string Gender {get;set;}
public string Address { get; set; }
public string Section { get; set; }
public int SchoolLevelID { get; set; }
public int SchoolYearID { get; set; }
public int AreaID { get; set; }
public int SchoolID { get; set; }
public int GradeLevelID { get; set; }
//Foreign Key - One to Many
public virtual SchoolLevel SchoolLevel { get; set; }
public virtual SchoolYear SchoolYear { get; set; }
public virtual Area Area { get; set; }
public virtual School School { get; set; }
public virtual GradeLevel GradeLevel{get;set;}
//Child is foreign key at the table
public virtual ICollection<Guardian> Guardians { get; set; }
}
public class SchoolLevel
{
public int SchoolLevelID { get; set; }
public string SchoolLevelName { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class SchoolYear
{
public int SchoolYearID { get; set; }
public string SchoolYearName { get; set; }
public virtual ICollection<Child> Children{get;set;}
}
public class Area
{
public int AreaID{get;set;}
public string AreaName { get; set; }
public virtual ICollection<Child> Children{get;set;}
}
public class School
{
public int SchoolID { get; set; }
public string SchoolName{get;set;}
public virtual ICollection<Child> Children { get; set; }
}
public class GradeLevel
{
public int GradeLevelID{get;set;}
public string GradeLevelName { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class ChildDbContext : DbContext
{
public DbSet<Child> Children { get; set; }
public DbSet<SchoolLevel> SchoolLevels { get; set; }
public DbSet<SchoolYear> SchoolYears { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<School> Schools { get; set; }
public DbSet<GradeLevel> GradeLevels { get; set; }
public DbSet<Guardian> Guardians { get; set; }
}
You can use this approach: Create a History model. That contains 1 changeness like o log.
public class History
{
public int HistoryId { get; set; }
public int ModelType { get; set; } //it is ModelTypeEnum value.
public int ModelId { get; set; }
public string PropertyName { get; set; }
public string Propertyvalue {get;set;}
public DateTime ChangeDate { get; set; }
public int ChangedUserId { get; set; }
}
And Enum:
public enum ModelTypeEnum
{
Child =1,
SchoolLevel = 2,
//etc..
};
For example, when you edit 1 Child entity, give changed properties name and value, it's id, type and others (ChangeDate, ChangedUserId) to History and save histories. If 3 properties will change you should save 3 history entities. Then, you can load (filter) histories by ModelId, by ChangedUserId etc.

Joins in Entity Framework 5

I have two classes in my model
[Table("tblPackages")]
public class Packages
{
public int Id { get; set; }
[Required]
[Display(Name = "Package Type")]
public int TypeId { get; set; }
[Display(Name = "No of SMS")]
public int AllowedSMS { get; set; }
[Display(Name = "Time Span in Days")]
public int? TimeSpan { get; set; }
public decimal Price { get; set; }
}
[Table("tblPackageTypes")]
public class PackageTypes
{
public int Id { get; set; }
public string Name { get; set; }
public string Details { get; set; }
public DateTime DueDate { get; set; }
}
and the table is same. now i need to get all from class Packages and just Name from class PackageTypes. How can i do by just using Entity Framework
Add a PackageTypes navigation property to your Packages class and access it by name:
[Table("tblPackages")]
public class Packages
{
public int Id { get; set; }
[Required]
[Display(Name = "Package Type")]
public int PackageTypesId { get; set; }
public PackageTypes PackageTypes { get; get; }
[Display(Name = "No of SMS")]
public int AllowedSMS { get; set; }
[Display(Name = "Time Span in Days")]
public int? TimeSpan { get; set; }
public decimal Price { get; set; }
}
By convention, Entity Framework will match the PackageTypesId and PackageTypes properties based on the naming (although you can use different names if you configure it to do so, but that's a more advanced topic).
Now you can access the Name directly from your Packages objects:
myPackage.PackageTypes.Name
Also, you might want to think about your classes in the singular, not the plural. The class represents a single Package, not the entire collection. Same with the PackageType. It makes your code more understandable:
Package myPackage = new Package();
myPackage.PackageType.Name
Only use plural if your class truly represents the entire collection and not a single item.
Use a navigation property, you will need a FK relationship between Packages and PackageTypes:
[Table("tblPackages")]
public class Packages
{
public int Id { get; set; }
[Required]
[Display(Name = "Package Type")]
public int TypeId { get; set; }
[Display(Name = "No of SMS")]
public int AllowedSMS { get; set; }
[Display(Name = "Time Span in Days")]
public int? TimeSpan { get; set; }
public decimal Price { get; set; }
public int PackageTypesId {get;set;}
public virtual PackageTypes {get;set;}
}
[Table("tblPackageTypes")]
public class PackageTypes
{
public int Id { get; set; }
public string Name { get; set; }
public string Details { get; set; }
public DateTime DueDate { get; set; }
public ICollection<Packages> {get;set;}
}
Like the previous answer states you need a navigation property. From your code I assume TypeId is FK to Id in PackageTypes. If this is so, simply create a property named Type of the type PackageType. When EF finds a navigation property to another entity it tries to find the property with the FK by appending the suffix Id or _Id.
If you on the other want a true composite object joining in fields from several tables you should use a view for this!
Regards
Håkan