Code first - Configure Navigation Not Working - Entity Framework - c#

I´m having a big problem to configure the navigation on my application.
These are the bases (but already with problems)
public class ModeloBase
{
[Key()]
public int Id { get; set; }
public int InseridoPorId { get; set; }
[Column(TypeName = "datetime2")]
public DateTime DataInserido { get; set; }
[Column(TypeName = "datetime2")]
public DateTime DataAtualizado { get; set; }
public bool Ativo { get; set; }
#region Navigation
[Required]
[ForeignKey("InseridoPorId")]
public virtual Colaborador InseridoPor { get; set; }
#endregion
}
public class Colaborador : ModeloBase
{
public Colaborador()
{
ColaboradoresSubordinadosPorMim = new HashSet<Colaborador>();
}
public int SuperiorId { get; set; }
[ForeignKey("SuperiorId")]
public Colaborador Superior { get; set; }
public ICollection<Colaborador> ColaboradoresSubordinadosPorMim { get; set; }
}
public class Contato : ModeloBase
{
[Required]
[StringLength(10)]
public string Endereco { get; set; }
}
Basically I have a base class "ModeloBase" that all extends it and I want that all thables have a FK to Colaborador with the Column Name "InseridoPorId"
As soon as I try to generate the controller it keep warning me with Multiplicity problems for these Navigation.
Any help?
Thanks.

Related

dotnet mvc relationships in post method

I have these tables: Sales, product, stock and salesProduct. I'm using a database first approach, they were created using EF scaffold. Sales table looks like this:
public partial class Sales
{
public Sales()
{
SalesProduct = new HashSet<SalesProduct>();
}
public int Id { get; set; }
public DateTime? CreationDate { get; set; }
public bool IndActive { get; set; }
public virtual ICollection<SalesProduct> SalesProduct { get; set; }
}
}
I need the post method on sales creation to create a SalesProduct object and add it to the database. I also need it to update the stock of that specific product.
Here are the other tables:
public partial class SalesProduct
{
public int Id { get; set; }
public int SaleId { get; set; }
public int ProductId { get; set; }
public decimal? Value { get; set; }
public bool IndActive { get; set; }
public virtual Produto IdProductNavigation { get; set; } = null!;
public virtual Vendum IdSalesNavigation { get; set; } = null!;
}
}
public partial class Stock
{
public int Id { get; set; }
public int IdProduct { get; set; }
public int? Quantitu { get; set; }
public bool IndActive { get; set; }
public virtual Product IdProductNavigation { get; set; } = null!;
}
}
How can i do that? I'm confused on how to deal with entity relationships in http methods!

Querying Repository with inheritance

I am using code first approach with Entity Framework 6. Three of my model classes implements inheritance and each of these model has collection which also implement inheritance. I am using TPH inheritance strategy. Everything works fine and I can insert/update with no problem at all. However, I get when I try to read data from the repo. The I get is shown below.
I have include my models, entity configuration and the line that throws this exception:
The include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the select operator for collection navigation properties
Code:
public abstract class OrderSup
{
public OrderSup()
{
DetailOrderSups = new HashSet<DetailOrderSup>();
}
public int Id { get; set; }
public string Description { get; set; }
public decimal AmountPaid { get; set; }
public DateTime DateEntered { get; set; }
public string CusSupCode { get; set; }
public decimal NetAmount { get; set; }
public decimal TaxAmount { get; set; }
public string DespatchSatus { get; set; }
public string Reference { get; set; }
}
public abstract class DetailOrderSup
{
[Key, Column(Order = 0)]
public virtual int OrderId { get; set; }
[Key, Column(Order = 1)]
public virtual int ProductId { get; set; }
public virtual Product OrderedProducts { get; set; }
public InvoiceType InvoiceType { get; set; }
public virtual OrderSup OrderSup { get; set; }
}
public class Order : OrderSup
{
public int SalesOrderNumber { get; set; }
public InvoiceType InvoiceType { get; set; }
}
public class PurchaseOrder : OrderSup
{
public string OrderStatus { get; set; }
//public string AlocationStatus { get; set; }
public int InvoiceNumber { get; set; }
}
public class PurchaseOrderDetails : DetailOrderSup
{
public bool IsOrderPaid { get; set; }
public decimal Outstanding { get; set; }
public decimal AmountPaid { get; set; }
public bool IsDisputed { get; set; }
}
public class OrderDetails: DetailOrderSup
{
public bool IsOrderPaid { get; set; }
public decimal Outstanding { get; set; }
}
public IEnumerable<PurchaseOrder> GetPurchaseOrders()
{
// THIS IS LINE THAT THROWS EXCEPTION
return this.AppContext.Orders.OfType<PurchaseOrder>()
.Include(o => o.DetailOrderSups.OfType<PurchaseOrderDetails>());
}
class OrderSupConfiguration : EntityTypeConfiguration<OrderSup>
{
public OrderSupConfiguration()
{
HasMany(p => p.DetailOrderSups)
.WithRequired(o => o.OrderSup)
.HasForeignKey(o => o.OrderId);
}
}
Please what am I doing wrong?
Thanks in advance for your assistance

Code-first Entity Framework may to many relation with additional fields not working

I have 3 classes that must be in a many-to-many relationship, but when I run my project, Entity Framework can't map them to SQL Server tables. I used migrations.
My user class is here:
[Table("tbl_User")]
public class User
{
public User()
{
}
#region Properties
[Key]
[Required][DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string LoginName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool EmailVerify { get; set; }
public string Image { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
public DateTime LoginDate { get; set; }
public bool Enabled { get; set; }
public bool Deleted { get; set; }
#endregion
#region Relations
public virtual IList<UserRole> UserRole { get; set; }
#endregion Relations
}
Role class is here:
[Table("tbl_Role")]
public class Role
{
public Role()
{
}
#region Properties
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string RoleName { get; set; }
public int Order { get; set; }
public string Icon { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
public bool Enable { get; set; }
public bool Deleted { get; set; }
#endregion Properties
#region Relations
public virtual IList<UserRole> UserRole { get;set;}
#endregion Relations
}
UserRole is my many-to-many relationship table:
[Table("tbl_UserRole")]
public class UserRole
{
internal class Configuration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<UserRole>
{
public Configuration()
{
HasRequired(current => current.User)
.WithMany(userrole => userrole.UserRole)
.HasForeignKey(fk => fk.UserId);
HasRequired(current => current.Role)
.WithMany(userrole => userrole.UserRole)
.HasForeignKey(fk => fk.RoleId);
}
}
public UserRole()
{
}
#region Properties
[Key]
[Required]
public long Id { get; set; }
public DateTime GrantDate { get; set; }
public DateTime ExpireDate { get; set; }
public bool Enabled { get; set; }
public bool Deleted { get; set; }
#endregion Properties
#region Relations
public long UserId { get; set; }
public virtual User User { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
#endregion Relations
}
and here is my database context
public class LiveMiracleDbContext:DbContext
{
public LiveMiracleDbContext() : base("LMConnection")
{
}
public DbSet<User> tbl_User { get; set; }
public DbSet<Role> tbl_Role { get; set; }
public DbSet<UserRole> tbl_UserRole { get; set; }
}
When I run my project without these classes, my database is generated, but when I use these classes, my database is not generated.
ok tanks for Gert Arnold comment
problem was in my Attributes this stracture is true
i removed attributes.

Self referencing entities with automapper

I have came across a problem where i need to map self referencing table from EF6 to DTO.
This is the table :
The Entity looks like this :
public partial class Page
{
public Page()
{
this.ChildPages = new HashSet<Page>();
}
public int PageId { get; set; }
public string Name { get; set; }
public string ModelName { get; set; }
public bool IsList { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
public System.DateTime DateCreated { get; set; }
public System.DateTime DateModified { get; set; }
public int Order { get; set; }
public Nullable<int> ParentPageId { get; set; }
public virtual ICollection<Page> ChildPages { get; set; }
public virtual Page ParentPage { get; set; }
}
The DTO Model looks like this :
public class PageViewModel
{
public int PageId { get; set; }
public string Name { get; set; }
public string ModelName { get; set; }
public bool IsList { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
public System.DateTime DateCreated { get; set; }
public System.DateTime DateModified { get; set; }
public virtual ICollection<PageViewModel> ChildPages { get; set; }
public virtual PageViewModel ParentPage { get; set; }
}
Automapper config looks like this:
config.CreateMap<Page, PageViewModel>().MaxDepth(8)
However when I run this code :
var pages = DB.Pages.ProjectTo<PageViewModel>().ToList();
I get the following exception:
An exception of type 'System.NotSupportedException' occurred in
EntityFramework.SqlServer.dll but was not handled in user code
Additional information: The type 'PageViewModel' appears in two
structurally incompatible initializations within a single LINQ to
Entities query. A type can be initialized in two places in the same
query, but only if the same properties are set in both places and
those properties are set in the same order.
Does anyone have an idea how to solve this issue?

ASP.Net MVC 5 EF6 - Allow nullables on two properties but force at least one to be present

In simple relational terms, I want each entry of ContractDetails to be assigned to either a Site OR a Company, not both at the same time, and one of them must be selected or there is no link at all. I'm not quite sure how to represent this in entity framework. My Model at Present:
Company Model:
public class Company
{
public int ID { get; set; }
public string Company_Name { get; set; }
public string Company_Prefix { get; set; }
public virtual ICollection<Site> Sites { get; set; }
}
Contract Details Model:
public class ContractDetails
{
public int ContractDetailsID { get; set; }
public int ContractTypeID { get; set; }
public int ContractRenewalPeriodID { get; set; }
public int? CompanyID { get; set; }
public int? SiteID { get; set; }
[Required, StringLength(10)]
public string Reference { get; set; }
[Display(Name = "Contract Start Date"), DataType(DataType.Date)]
public DateTime? Contract_Start_Date { get; set; }
[Display(Name = "Contract End Date"), DataType(DataType.Date)]
public DateTime? Contract_End_Date { get; set; }
[Column(TypeName = "text")]
public string Notes { get; set; }
public string Direct_Debit_Reference { get; set; }
public virtual Company Company { get; set; }
public virtual Site Site { get; set; }
public virtual ContractType ContractType { get; set; }
public virtual ContractRenewalPeriod ContractRenewalPeriod { get; set; }
}
Site Model:
public class Site
{
public int ID { get; set; }
public string Site_Name { get; set; }
public string Site_TelephoneNumber { get; set; }
public string Site_City { get; set; }
public int CompanyID { get; set; }
public virtual Company Company { get; set; }
}
Just implement the IValidatableObject on ContractDetails class. On Validate method put the validation logic. If the object is not valid you must return a collection of ValidationResult. when saving the object, EF will execute the Validate method and verify that your ContractDetails object is coherent.

Categories

Resources