C# MVC Model view connecting 2 different database columns - c#

This is the first time I have attempted to join information from one database to the other. I have a accounting database and a regular site database. Trying to keep them separate. I have a page that shows Transactions but am getting the information for a few of the columns from the regular database by way of Id's. Below is my Model. I am showing nothing in the fields for the items in the other database.
public class Transaction
{
[Key]
public Guid TransactionId { get; set; }
public string Description { get; set; }
public int? CompanyId { get; set; }
public Guid? VendorId { get; set; }
public string InCheckNumber { get; set; }
public string OutCheckNumber { get; set; }
public string InvoiceNumber { get; set; }
public string PurchaseOrderNumber { get; set; }
public Guid LedgerAccountId { get; set; }
public decimal? DebitAmount { get; set; }
public decimal? CreditAmount { get; set; }
public DateTime TransactionDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public string SavedDocument { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
public bool IsCredit { get; set; }
public bool IsDebit { get; set; }
public Guid Type { get; set; }
[ForeignKey("LedgerAccountId")]
public LedgerAccount LedgerAccount { get; set; }
[ForeignKey("CompanyId")]
public CompanyNames Company { get; set; }
[ForeignKey("VendorId")]
public Vendors Vendor { get; set; }
}
I have added the 'using' of the General.Entities to this model. Is there something else i need to add for this?
Thanks in advance.
UPDATE:
See Question - Link to answer of question

Related

EF Core - Unable to determine the relationship represented by navigation (One-to-Many)

I am trying to create a simple One-to-many relationship but Ef Core somehow does not recognize it. I am still a beginner in this but I think I did this by the book (defined the relationship fully) so I don't get why EF Core is throwing this error:
Unable to determine the relationship represented by navigation
'Asset.Insurance' of type 'Insurance'. Either manually configure the
relationship, or ignore this property using the '[NotMapped]'
attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Those are my two models:
Asset.cs
public class Asset
{
public int AssetId { get; set; }
public string AssetName { get; set; }
[ForeignKey("AssetTypeId")]
public int AssetTypeId { get; set; }
public AssetType AssetType { get; set; }
public ICollection<AssetValue> AssetTypeValues { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public string SerialNumber { get; set; }
public string ProductNumber { get; set; }
public DateTime PurchaseDate { get; set; }
public decimal PurchasePrice { get; set; }
[ForeignKey("LocationId")]
public int? LocationId { get; set; }
public Location Location { get; set; }
[ForeignKey("InsuranceId")]
public int InsuranceId { get; set; }
public Insurance Insurance { get; set; }
[ForeignKey("OwnerId")]
public string? OwnerId { get; set; }
public AppUser Owner { get; set; }
[ForeignKey("InvoiceId")]
public int? InvoiceId { get; set; }
public Insurance Invoice { get; set; }
public string? ImagePath { get; set; }
public string? Description { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
Insurance.cs
public class Insurance
{
public int InsuranceId { get; set; }
[ForeignKey("InsuranceTypeId")]
public int InsuranceTypeId { get; set; }
public InsuranceType InsuranceType { get; set; }
public string Insurer { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string? FilePath { get; set; }
public string? Description { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public ICollection<Asset> Assets { get; set; }
}
Also, if I remove this relationship, just for testing, migration still doesn't work and throwing errors about the other foreign keys in the Asset model. Is it because I have too many foreign keys so I have to define them in OnModelCreating?
Edit: ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<AppUser>
{
public DbSet<Asset> Assets { get; set; }
public DbSet<AssetType> AssetTypes { get; set; }
public DbSet<AssetProp> AssetProps { get; set; }
public DbSet<AssetValue> AssetValues { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<CompanyContact> CompanyContacts { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<InsuranceType> InsuranceTypes { get; set; }
public DbSet<Insurance> Insurances { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
If you specify the [ForeignKey] attribute, you need to do one of two things:
Add the attribute to the scalar property, and use the name of the navigation property; or
Add the attribute to the navigation property, and use the name of the scalar property.
So either:
[ForeignKey("Insurance")]
public int InsuranceId { get; set; }
public Insurance Insurance { get; set; }
or:
public int InsuranceId { get; set; }
[ForeignKey("InsuranceId")]
public Insurance Insurance { get; set; }
By putting the attribute on the scalar property and specifying the name of the scalar property, EF can't understand what you're trying to do.
This applies to all of your [ForeignKey("...")] attributes in the code.
NB: Since there is only one navigation property to each given entity type, and the scalar property names match the navigation property names with the Id suffix added, the [ForeignKey] attributes aren't actually required.
EDIT:
You have two navigation properties for the Insurance entity:
public Insurance Insurance { get; set; }
...
public Insurance Invoice { get; set; }
I suspect the second one should be:
public Invoice Invoice { get; set; }

EF CORE understanding relationships in a Gym setting

Ok I am kinda stuck I need a ef query that will get me the following data.
I have sessions which are created at the Gym I am using ef core here so
In the main grid I need to list the students that our their for the workout that day.
ID
Session Name
Start Date
TeamId
1
Test 1
06/11/2021
1
---
2
Test 2
05/11/2021
2
---
I have table Students which has a team Id
ID
FirstName
Last Name
TeamId
1
Matt
Smith
1
---
2
Martha
Jones
2
---
Team Includes the students and is linked back to the Student via Team Id
ID
Name
Session Id
1
Test Team
1
!2
Test Team 2
2
For Example what I want to be able to do is Pick the session that is on the start date of the 5 and display only the students attending that day.
My Poco Class for Session
public class Session
{
public int Id { get; set; }
public string? Name { get; set; }
public int OccuranceType { get; set; }
public int? StaffId { get; set; }
public int? Day { get; set; }
public int? Duration { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int? Status { get; set; }
public int? TeamId { get; set; }
public Team? Team { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
Student
public class Student
{
public int Id { get; set; }
public int? Type { get; set; }
public int? CoachId { get; set; }
public virtual Coach Coach { get; set; }
public int? TeamId { get; set; }
public virtual Team Team { get; set; }
public string? FirstName { get; set; }
public string? Surname { get; set; }
public DateTime? DOB { get; set; }
public decimal? Weight { get; set; }
public decimal? Height { get; set; }
public int? Gender { get; set; }
public string? Photo { get; set; }
public int? Age { get; set; }
public string? AddressLine1 { get; set; }
public string? AddressLine2 { get; set; }
public string? State { get; set; }
public string? ZipCode { get; set; }
public string? Mobile { get; set; }
public string? EmailAddress { get; set; }
public ICollection<ConditioningWorkout> ConditioningWorkouts { get; set; }
public ConditioningWorkout? ConditioningWorkout { get; set; }
public ICollection<Booking> Bookings { get; set; }
public ICollection<BikeWorkOut> BikeWorkOuts { get; set; }
public bool? IsDeleted { get; set; }
public ICollection<Notes>? Notes { get; set; }
public decimal? TB { get; set; }
public decimal? OP { get; set; }
public decimal? PU { get; set; }
public decimal? PB { get; set; }
public decimal? BP { get; set; }
public int Status { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
Team
public class Team
{
public int Id { get; set; }
public Guid? UserId { get; set; }
public Guid? TennantId { get; set; }
public string Name { get; set; }
public int? CoachId { get; set; }
public virtual Coach Coach { get; set; }
public ICollection<Student> Students { get; set;}
public bool? IsDeleted { get; set; }
public int? SessionId { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
I think I need to have some link back from the Student to the session but because they can block book sessions and team level I dont no how to achieve this.
It looks like a Session has a Team(s?) and a Team has a Student(s), so it's reasonably straight forward:
context.Sessions.Include(s => s.Team).ThenInclude(t => t.Students)
.Where(s => s.StartDate == new DateTime(2021, 11, 5))
This gets you a collections of sessions that should have their Team property populated with a Team, and in turn that Team has a Students collection that is populated with Students

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.

How to properly add a foreign key from my own model to the EF Userprofile?

my model classes first:
public class Person
{
[Required, Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LearntSkillsAndLevelOfSkills { get; set; }
public string ProfileImage { get; set; }
public string City { get; set; }
public string PhoneNr { get; set; }
[Required]
public string Email { get; set; }
public string Hobbys { get; set; }
public string SkillsToLearn { get; set; }
public string Stand { get; set; }
public int YearsOfWorkExperience { get; set; }
public string HobbyProjectICTRelated { get; set; }
public string ExtraInfo { get; set; }
public string Summary { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile profile { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public Nullable<int> ID { get; set; }
public virtual Person personprofile { get; set; }
}
when i run this however it gives me this exception: The principal end of this association must be explicitly configured
i've searched this error but it doesn't clarify it for me... so i absolutely have no clue how to fix this. Basically i want to link my Person class to the Userprofiles so that i can create a login mechanism that automatically lets 1 person who makes an account on the site get 1 Profile to Edit to his own information. He's however not allowed to modify other people their accounts.
I hope this makes my problem clear and that somebody can help me :). i'm using EF 6 btw and i get the error in the class InitializeSimpleMembershipAttribute that comes standard with the MVC example of ASP.net
Greetings and thanks in advance,
Marijn
I managed to get it working with these codes in the models:
[Table("UserProfile")]
public class UserProfile
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual Person personprofile { get; set; }
}
public class Person
{
[ForeignKey("profile"), Key]
public int UserId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LearntSkillsAndLevelOfSkills { get; set; }
public string ProfileImage { get; set; }
public string City { get; set; }
public string PhoneNr { get; set; }
[Required]
public string Email { get; set; }
public string Hobbys { get; set; }
public string SkillsToLearn { get; set; }
public string Stand { get; set; }
public int YearsOfWorkExperience { get; set; }
public string HobbyProjectICTRelated { get; set; }
public string ExtraInfo { get; set; }
public string Summary { get; set; }
public UserProfile profile { get; set; }
}

EF4.1 Code First Question

I want to create my first application using the EF 4.1 Code First Model. I want to model a magazine subscription but just want to check that my POCO classes are fit for purpose.
The following are my classes. Am I missing anything?
Should Customer be a member of Subscription or should it be just that List be a member of Customer?
Thanks.
public class Subscription
{
public int SubscriptionID { get; set; }
public string CardNumber { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public decimal NetPrice { get; set; }
public decimal Tax { get; set; }
public decimal Discount { get; set; }
public string PromotionalCode { get; set; }
public Customer Customer{ get; set; }
}
public class Customer {
public int CustomerID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public PostalAddress PostalAddress { get; set; }
public string EmailAddress { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public DateTime DateOfBirth { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public bool Valid { get; set; }
public IList<Subscription> Subscriptions { get; set; }
public bool MailMarketing { get; set; }
public bool PartnerMailMarketing { get; set; }
}
public class PostalAddress
{
public int ID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
public string Region { get; set; }
public string Country { get; set; }
}
If a Customer have X suscriptions, every suscription should have the customerID so you need that in your Suscription class (public int CustomerID {get; set;}).
OTOH, I think that you have to put that Customer reference as virtual and the suscription one (I don't know why).
Maybe Im wrong but that works for me.
Anyway, what's your problem?
Your models look correct. You don't necessarily need the Customer property in the Subscription class, but it does help if you want to retrieve a specific Subscription and then want to find the customer that is tied to that subscription. In that instance you can then do var customer = mySub.Customer instead of querying for a customer with the specific subscription id.

Categories

Resources