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
Related
So I'm trying to create a simple Product-Preview 1 to 1 relationship as follows:
public class Product : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string name { get; set; }
public virtual EPS eps { get; set; }
public virtual Preview preview { get; set; }
[ForeignKey("userId")]
public virtual User user { get; set; }
public Guid userId { get; set; }
}
and
public class Preview : BaseEntity
{
[Key,ForeignKey("Product")]
public Guid Id { get; set; }
public string imagePath { get; set; }
public double width { get; set; }
public double height { get; set; }
public virtual List<TextPreview> Texts { get; set; }
public virtual List<ImagePlaceHolder> ImagePlaceHolders { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
public virtual Guid ProductId { get; set; }
}
I was expecting to have a foreign key in the Previews table that would point to a Product
but after running the migration I just get it as regular field
What I'm I doing wrong?
You almost have it you just missed one piece of the puzzle ...
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
You also need to add ...
public Guid ProductId { get; set; }
to the preview object.
It's also worth noting that the ForeignKey attrib can be put on either property, and the string must refer to the other one of the pair.
As it's currently written you are trying to make the Id property specify the value for both the primary key and the foreign key on the tables in question.
So your final code might look something like ...
public class Product : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[ForeignKey("User")]
public Guid UserId { get; set; }
public string name { get; set; }
public virtual EPS eps { get; set; }
public virtual Preview preview { get; set; }
public virtual User user { get; set; }
}
and
public class Preview : BaseEntity
{
[Key]
public Guid Id { get; set; }
[ForeignKey("Product")]
public Guid ProductId { get; set; }
public string imagePath { get; set; }
public double width { get; set; }
public double height { get; set; }
public virtual List<TextPreview> Texts { get; set; }
public virtual List<ImagePlaceHolder> ImagePlaceHolders { get; set; }
public virtual Product Product { get; set; }
}
As a side note I would also recommend against using concrete collection types like List<T> instead use something like IList<T> or ICollection<T> it promotes better code reuse and extensibility.
I am working on ASP.NET Core application which uses Entity framework core. I am using code first approach to create database model. I am trying the get one-to-many relationship (one user can have multiple products) between following two classes but in database diagram, I can not see that relationship.
public class SystemUser : IdentityUser
{
public SystemUser()
{
this.ProductToUser = new HashSet<ProductsToUser>();
}
[StringLength(200)]
[Required]
public string FullName { get; set; }
[Required]
[StringLength(200)]
public string Address { get; set; }
[Required]
public int PinNo { get; set; }
[Required]
public int StateId { get; set; }
[Required]
public int CountryId { get; set; }
[Required]
public DateTime RegisterDate { get; set; }
public virtual ICollection<ProductsToUser> ProductToUser { get; set; }
}
public class ProductsToUser
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string UserId { get; set; }
[Required]
public int ProductID { get; set; }
[ForeignKey("UserId")]
public SystemUser SystemUser { get; set; }
}
Below is the screenshot of database diagram.
As you can see in diagram it is not showing relationship. But I am getting foreign key constraint in ProductsToUser table as shown below
How do I resolve this issue?
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.
I'm trying to learn how to use the ASP.NET MVC 4 and Entity FrameWork 5, and I'm a bit confused by scaffolding for Drop Down Lists.
I have three classes:
public class ScopeType
{
public int ScopeTypeId { get; set; }
[Required]
public string Type { get; set; }
}
public class ScopeManufacturer
{
public int ScopeManufacturerId { get; set; }
[Required]
[Display(Name="Manufacturer Name")]
public string Name { get; set; }
}
public class Scope
{
public int ScopeId { get; set; }
[Required]
public ScopeManufacturer ScopeManufacturer { get; set; }
[Required]
public string Name { get; set; }
[Required]
public ScopeType ScopeType { get; set; }
[Required]
public int Aperture { get; set; }
[Required]
public int FocalLength { get; set; }
}
Essentially, the first two classes are just lists of values that I want to appear in the drop downs on the 'Scope' create/edit forms. It's a 1 to 1 relationship.
I build the solution, and then add scaffolded controllers and views. Unfortunately, for the 'Scope' controller and views, the ScopeType and ScopeManufacturer navigation properties are ignored; no drop down lists are generated.
I then found on Google examples where people describe specifying the relationship between items by creating properties of integers, with the same name as the Id on the related thing. Therefore, I deleted the controllers and views, and tried again with:
public class Scope
{
public int ScopeId { get; set; }
[Required]
public int ScopeManufacturerId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int ScopeTypeId { get; set; }
[Required]
public int Aperture { get; set; }
[Required]
public int FocalLength { get; set; }
}
This still didn't scaffold drop down lists for me - rather, it gave me 2 extra fields for me to type integers into.
What am I doing wrong, or am I mistaken in believing that the scaffolding in MVC 4 will generate drop down lists for 1 to 1 relationships like that?
I have created an MVC4 web application using EF-database-first. The tables have composite keys [ID, Name, EffDate], and no foreign keys defined in the database:
For example, Department partial class:
[MetadataType(typeof(DepartmentMetadata))]
public partial class Department
{
public int DeptID { get; set; }
public string DeptName { get; set; }
public System.DateTime EffDate { get; set; }
public string Status { get; set; }
public string RevenueAccount { get; set; }
}
Department metadata class:
public class DepartmentMetadata
{
[Required]
public int DeptID { get; set; }
[Required]
[Display(Name = "Department Name")]
public string DeptName { get; set; }
[Required]
[Display(Name = "Effective Date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", NullDisplayText = "--", ConvertEmptyStringToNull = true)]
public System.DateTime EffDate { get; set; }
[Required]
public string Status { get; set; }
[Display(Name = "Revenue Account")]
[StringLength(10)]
public string RevenueAccount { get; set; }
}
The Allocation table, that refers to the Department table. It also has a composite key [DeptID, ProjectID, BillableUnitID, EffDate]. If I could, I would declare the DeptID field a foreign key ...but I don't control the database, and more importantly I believe T-SQL won't allow foreign keys to part of a composite key:
[MetadataType(typeof(AllocationMetadata))]
public partial class Allocation
{
public int DeptID { get; set; }
public int ProjectID { get; set; }
public int BillableUnitID { get; set; }
public System.DateTime EffDate { get; set; }
public string Status { get; set; }
public decimal Allocation1 { get; set; }
}
This works, but I get a column of DeptID numbers. What I would like to have is a column of department names.
A previous question directed me to virtual navigation properties, so I added them:
[MetadataType(typeof(AllocationMetadata))]
public partial class Allocation
{
[ForeignKey("Department")]
public int DeptID { get; set; }
public int ProjectID { get; set; }
public int BillableUnitID { get; set; }
public System.DateTime EffDate { get; set; }
public string Status { get; set; }
public decimal Allocation1 { get; set; }
public virtual Department Department { get; set; } /* navigation property */
}
The code in the AllocationController for Index is:
public ActionResult Index()
{
return View(db.Allocation.Include(a => a.Department).ToList());
}
When I click on the link to Allocation Index view, I get this error message (after I Stop Debugging):
Server Error in '/' Application.
A specified Include path is not valid. The EntityType
'KC_BillableUnit_TESTModel.Allocation' does not declare a navigation
property with the name 'Department'.
Stack trace
[InvalidOperationException: A specified
Include path is not valid. The EntityType
'KC_BillableUnit_TESTModel.Allocation' does not declare a navigation
property with the name 'Department'.]
System.Data.Objects.Internal.ObjectFullSpanRewriter.ConvertSpanPath(SpanPathInfo
parentInfo, List`1 navPropNames, Int32 pos) +8355128
System.Data.Objects.Internal.ObjectFullSpanRewriter..ctor(DbCommandTree
tree, DbExpression toRewrite, Span span) +256
....continues....
I've tried various combinations of annotations, but all result in the same error.
How can I get my Allocation list to show Department names instead of DeptID numbers?
Off course you can! I think the problem is that your declared the navigation property just in one side (Allocation), however you must declare that at both sides (Department too).
The following must resolve your problem:
[MetadataType(typeof(DepartmentMetadata))]
public partial class Department
{
public Department()
{
this.Allocations = new HashSet<Allocation>();
}
// properties ...
public virtual ICollection<Allocation> Allocations { get; set; }
}