C# Entity Framework - Multiple relationships - c#

I'm not sure if this is possible or not, but I thought I would ask...
I have two database tables. One is a list of users pulled from Active Directory. The second table is a list of scheduled forwards. The relationship I would like to create would be...
public class AdObject
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string ObjectType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
public string PrimaryEmail { get; set; }
public string Alias { get; set; }
public string SamAccountName { get; set; }
public string PrimaryDisplay { get; set; }
public string CanonicalName { get; set; }
public string OU { get; set; }
public string CoreGroup { get; set; }
public string ForwardedTo { get; set; }
public bool? IsDisabled { get; set; }
public bool? IsForwarded { get; set; }
public bool? DeliverAndRedirect { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public DateTime? LastLogon { get; set; }
public DateTime? LastApiLogon { get; set; }
public DateTime? LastCheck { get; set; }
// This isn't required. But if possible I would like this to be
// a relationship to another AdObject whos "PrimaryEmail" matches
// the "ForwardedTo" column of this AdObject. There will not always
// be a match though, so not too important just wondering if its possible.
public AdObject ForwardedToObject { get; set; }
// This would be a list of forwards where the "ForwardFrom"
// column matches the "PrimaryEmail" of this AdObject.
public ICollection<Forward> ScheduledForwards { get; set; }
= new List<Forward>();
// FYI... Technically ID,SamAccountName,PrimaryEmail,DistinguishedName,
// and CanonicalName are all unique. They could all be keys.
}
public class Forward
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string ForwardFrom { get; set; }
public string ForwardTo { get; set; }
public bool? DeliverAndRedirect { get; set; }
public DateTime? StartTime { get; set; }
public DateTime? StopTime { get; set; }
public string Recurrence { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public string StartJobId { get; set; }
public string StopJobId { get; set; }
public string StartJobStatus { get; set; }
public string StopJobStatus { get; set; }
public DateTime? StartJobCompleted { get; set; }
public DateTime? StopJobCompleted { get; set; }
public DateTime? StartJobCreated { get; set; }
public DateTime? StopJobCreated { get; set; }
public string StartReason { get; set; }
public string StopReason { get; set; }
// This would be the AdObject whos "PrimaryEmail" matches the
// "ForwardTo" column.
public AdObject ForwardToObject { get; set; }
// This would be the AdObject whos "PrimaryEmail" matches the
// "ForwardFrom" column.
public AdObject ForwardFromObject { get; set; }
}

I think I got it figured out. I was having a hell of a time understanding the logic behind relationships. I had a few misconceptions that I ironed out and after going through every YouTube video, PluralSight Course and Udemy course I could find it finally started to click. I usually don't have this much trouble teaching myself these things, but the misconceptions I had were pointing me in the wrong direction. In the end I only had to specify the keys and two relationships (conventions did the rest).
public class AdObject
{
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string ObjectType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
[Key, Column(Order = 1)]
public string PrimaryEmail { get; set; }
public string Alias { get; set; }
public string SamAccountName { get; set; }
public string PrimaryDisplay { get; set; }
public string CanonicalName { get; set; }
public string OU { get; set; }
public string CoreGroup { get; set; }
public bool? IsDisabled { get; set; }
public bool? IsForwarded { get; set; }
public bool? DeliverAndRedirect { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public DateTime? LastLogon { get; set; }
public DateTime? LastApiLogon { get; set; }
public DateTime? LastCheck { get; set; }
public AdObject ForwardedToObject { get; set; }
public ICollection<Forward> ForwardRecipientSchedule { get; set; }
= new List<Forward>();
public ICollection<Forward> ForwardSchedule { get; set; }
= new List<Forward>();
}
public class Forward
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public AdObject ForwardFromObject { get; set; }
public AdObject ForwardToObject { get; set; }
public bool? DeliverAndRedirect { get; set; }
public DateTime? StartTime { get; set; }
public DateTime? StopTime { get; set; }
public string Recurrence { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public string StartJobId { get; set; }
public string StopJobId { get; set; }
public string StartJobStatus { get; set; }
public string StopJobStatus { get; set; }
public DateTime? StartJobCompleted { get; set; }
public DateTime? StopJobCompleted { get; set; }
public DateTime? StartJobCreated { get; set; }
public DateTime? StopJobCreated { get; set; }
public string StartReason { get; set; }
public string StopReason { get; set; }
}
public class EntityContext : DbContext
{
public EntityContext() : base("name=EnityContext"){
}
public DbSet<AdObject> AdObjects { get; set; }
public DbSet<Forward> Forwards { get; set; }
//protected override void OnConfiguring(DbContext)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AdObject>()
.HasMany(f => f.ForwardSchedule)
.WithRequired(f => f.ForwardFromObject)
.WillCascadeOnDelete(false);
modelBuilder.Entity<AdObject>()
.HasMany(f => f.ForwardRecipientSchedule)
.WithRequired(f => f.ForwardToObject)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
}

Related

Display two table data in one

Hi doing a master details and currently in the process of display two tables data based on invoice number but I have this error
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
{"Invalid column name 'klsm_Invoice_InternalInvoiceNo'.\r\nInvalid column name 'klsm_Invoice_InternalInvoiceNo'.\r\nInvalid column name 'klsm_Invoice_InternalInvoiceNo'."}
I am following Tutorial: Implement CRUD Functionality with the Entity Framework in ASP.NET MVC but I have come to a problem.
Desc class
[Table("klsm_InvoiceDesc")]
public class Desc
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public int DescNo { get; set; }
public string Principal { get; set; }
public string ChargeCode { get; set; }
public string Quantity { get; set; }
public string Description { get; set; }
public string UnitPrice { get; set; }
public string Amount { get; set; }
public string ForeignAmount { get; set; }
public string EL1 { get; set; }
public string EL2 { get; set; }
public string ShortName { get; set; }
public string InvoiceType { get; set; }
public string PONumber { get; set; }
public string Batch { get; set; }
public string CCVBatch { get; set; }
public string PaidAmount { get; set; }
public string Paid { get; set; }
public string TT { get; set; }
public string BankCode { get; set; }
//public string Id { get; set; }
public virtual College klsm_Invoice{ get; set; }
}
College class
[Table("klsm_Invoice")]
public class College
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public decimal Amount { get; set; }
public decimal ForeignAmount { get; set; }
public string UserCreated { get; set; }
public string UserModified { get; set; }
public int AccMonth { get; set; }
public int AccYear { get; set; }
public string AccStatus { get; set; }
public string Status { get; set; }
public string PaidStatus { get; set; }
public string Principal { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public string EL1 { get; set; }
public string InvoiceType { get; set; }
public string CurrencyType { get; set; }
public decimal ExchangeRate { get; set; }
public string GSTChecked { get; set; }
public DateTime PaymentSchedule { get; set; }
public string PaymentMode { get; set; }
public string CashAdvance { get; set; }
public virtual ICollection<Desc> klsm_InvoiceDesc { get; set; }
}
Home Controller
public ActionResult Details(string id)
{
College klsm_Invoice = db.klsm_Invoice.Find(id);
return View(klsm_Invoice);
}

Map multiple different models into single View Model - AutoMapper

I am trying to map multiple Userprofile models into a single viewModel. At a time only one user data will be mapped.
In the below code snippet I mentioned the use case that I already tried.
Also, I try to AutoMapper.Map<source,target> but didn't work for me.
//This is one FarmerUser Model
public partial class FarmerProfileModel
{
public long FarmerId { get; set; }
public string FarmerName { get; set; }
public string FatherHusbandName { get; set; }
public string Cnic { get; set; }
public string Gender { get; set; }
public string CellPhone { get; set; }
public string PresentAddress { get; set; }
public string PermanentAddress { get; set; }
public int? EducationCode { get; set; }
public int? MaleDependant { get; set; }
public int? FemaleDependant { get; set; }
public string AlternateName { get; set; }
public string AlternateCellPhoneNo { get; set; }
public string AlternateRelationshipwithFarmer { get; set; }
public int? ReferalCode { get; set; }
public string FarmerImage { get; set; }
public string UnionCouncil { get; set; }
public string MozaName { get; set; }
public int? SmallAnimals { get; set; }
public int? BigAnimals { get; set; }
public int? Tractor { get; set; }
public Guid? UserGuid { get; set; }
public DistrictCodeModel DistrictCodeNavigation { get; set; }
public TehsilCodeModel TehsilCodeNavigation { get; set; }
}
Another Model of the Tso User
public class TsoProfileModel
{
public long Tsoid { get; set; }
public string Tsoname { get; set; }
public string Cnic { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
public string AlternateCellPhone { get; set; }
public string Landline { get; set; }
public string Gender { get; set; }
public string Tsoimage { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public DateTime? InsertionDate { get; set; }
public string ActiveStatus { get; set; }
public Guid? UserGuid { get; set; }
public TbDistrictCode DistrictCodeNavigation { get; set; }
public TbTehsilCode TehsilCodeNavigation { get; set; }
}
This is my ViewModel in which i am trying to incorporrate my data of Farmer/Tso
public class UserProfileInfo
{
public long? UserId { get; set; }
public string UserName { get; set; }
public string Cnic { get; set; }
public string Email { get; set; }
public string AlternateCellPhone { get; set; }
public string Landline { get; set; }
public string Gender { get; set; }
public string PresentAddress { get; set; }
public string PermanentAddress { get; set; }
public int? EducationCode { get; set; }
public string image { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public DateTime? InsertionDate { get; set; }
public string ActiveStatus { get; set; }
public Guid? UserGuid { get; set; }
public string FatherHusbandName { get; set; }
public string CellPhone { get; set; }
public int? MaleDependant { get; set; }
public int? FemaleDependant { get; set; }
public string AlternateName { get; set; }
public string AlternateRelationshipwithFarmer { get; set; }
public int? ReferalCode { get; set; }
public string UnionCouncil { get; set; }
public string MozaName { get; set; }
public int? SmallAnimals { get; set; }
public int? BigAnimals { get; set; }
public int? Tractor { get; set; }
public string Role { get; set; }
public DistrictCodeModel DistrictCodeNavigation { get; set; }
public TehsilCodeModel TehsilCodeNavigation { get; set; }
}
Below is the code I am trying to use.
if (User=="farmer")
{
var tbFarmerInfo = await
_farmerService.GetFarmerByCellPhone(cellno);
var result = _Mapper.Map<UserProfileInfo>(tbFarmerInfo);
result.UserId = tbFarmerInfo.FarmerId;
result.UserName = tbFarmerInfo.FarmerName;
result.image = tbFarmerInfo.FarmerImage;
result.Role = "Farmer";
response.Data = result;
return response;
}
else if (User == "TSO")
{
string cellno = User.Claims.FirstOrDefault(c => c.Type ==
ClaimTypes.Name).Value.TrimStart('0');
var tbTsoInfo = await _tsoService.GetTSOByCellPhone(cellno);
var result = _Mapper.Map<UserProfileInfo>(tbTsoInfo);
result.UserId = tbTsoInfo.Tsoid;
result.UserName = tbTsoInfo.Tsoname;
result.image = tbTsoInfo.Tsoimage;
result.Role = "TSO";
response.Data = result;
return response;
}
The expected result should be that both models can be mapped in the viewModel.
Like, if I map the FarmerProfile it should be mapped and if I want to map TsoProfile it should be mapped too.

Invalid column name: "ColumnName#" with a suffix number

I have a table Users:
I am using Entity Framework 6 to make the type configuration
public class UsersMapping : EntityTypeConfiguration<Users>
{
public UsersMapping()
{
HasKey(t => t.UserID);
Property(t => t.UserID).IsRequired();
ToTable("Users", "dbo");
Property(t => t.Id).HasColumnName("UserID");
}
}
and this is the Users class:
public class Users : EntityBase
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public DateTime DateCreated { get; set; }
public byte[] Timestamp { get; set; }
public byte[] Password { get; set; }
public DateTime? DateActivated { get; set; }
public bool LockedOut { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int? State { get; set; }
public string Zip { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public bool? ReportServiceAccount { get; set; }
public string CompanyName { get; set; }
public int? ILAC { get; set; }
public string BioFingerprint { get; set; }
public string Title { get; set; }
public string Squad { get; set; }
public byte[] SignatureFile { get; set; }
public byte? CETGroupID { get; set; }
public string TokenID { get; set; }
public int? Pin { get; set; }
public string RadioNr { get; set; }
}
public class EntityBase
{
public int Id { get; set; }
}
I am trying to set the Id field as primary because my repository pattern works using the field Id that is not present on this case in the table. But when I am trying to get the set of users I get this error:
The column name is invalid UserID1
The weird thing to me is the #1 that is at the end. What I am doing wrong?

How to use Fluent API to map foreign key

I am trying to use modelBuilder to map a foreign Key in my database. I need to post the Id into JobTESPM_EmployeeId instead of JOBTESPMId. I have been using this a guide but I can't see where the examples are the same as my setup. http://msdn.microsoft.com/en-in/data/jj591620.aspx#IndependentAssociation
public class Job
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public Int64? JobId { get; set; }
public int? JobNumber { get; set; }
public string JobName { get; set; }
public int? JobTypeId { get; set; }
public int? CustomerEmployeePMId { get; set; }
public virtual CustomerEmployee CustomerEmployeePM { get; set; }
public int? CustomerEmployeeAdminId { get; set; }
public virtual CustomerEmployee CustomerEmployeeAdmin { get; set; }
public int? CustomerEmployeeAccountantId { get; set; }
public virtual CustomerEmployee CustomerEmployeeAccountant { get; set; }
public int? CustomerEmployeeSuperintendentId { get; set; }
public virtual CustomerEmployee CustomerEmployeeSuperintendent { get; set; }
public int? JobTESPMId { get; set; }
public virtual Employee JobTESPM { get; set; }
public int? JobTESSuperintendentId { get; set; }
public virtual Employee JobTESSuperintendent { get; set; }
}
public class Employee
{
public int EmployeeId { get; set; }
public string AccountName { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeeLastName { get; set; }
public string EmployeeTitle { get; set; }
public Int64? EmployeeCellPhone { get; set; }
public Int64? EmployeeOfficePhone { get; set; }
public string EmployeeEmail { get; set; }
public int? CompanyEmployeeId { get; set; }
public bool? EmployeeHidden { get; set; }
public bool? EmployeeIsSuper { get; set; }
public bool? EmployeeIsPM { get; set; }
public string EmployeeAltEmail { get; set; }
}
What about adding a couple attributes...
[Column("JobTESPM_EmployeeID")]
public int? JobTESPMId { get; set; }
[ForeignKey("JobTESPMId")]
public virtual Employee JobTESPM { get; set; }

How to parse Json from the RootObject?

I am trying to parse JSON response so I created some classes.
Actually I want Leg and Flight class element value. I am trying to get those element value from RootObject but I don't know how to do this. I googled but I am little bit confuse.
I paste my JSON respose , Classes !!
JSON Response :
http://pastebin.com/fjjLxkd2
Classes :
public class Detail
{
}
public class Airport
{
public string kind { get; set; }
public string code { get; set; }
public string city { get; set; }
public string name { get; set; }
}
public class City
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Aircraft
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Tax
{
public string kind { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Carrier
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Data
{
public string kind { get; set; }
public List<Airport> airport { get; set; }
public List<City> city { get; set; }
public List<Aircraft> aircraft { get; set; }
public List<Tax> tax { get; set; }
public List<Carrier> carrier { get; set; }
}
public class Flight
{
public string carrier { get; set; }
public string number { get; set; }
}
public class Leg
{
public string kind { get; set; }
public string id { get; set; }
public string aircraft { get; set; }
public string arrivalTime { get; set; }
public string departureTime { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string originTerminal { get; set; }
public int duration { get; set; }
public int onTimePerformance { get; set; }
public int mileage { get; set; }
public string meal { get; set; }
public bool secure { get; set; }
public string destinationTerminal { get; set; }
public string operatingDisclosure { get; set; }
}
public class Segment
{
public string kind { get; set; }
public int duration { get; set; }
public Flight flight { get; set; }
public string id { get; set; }
public string cabin { get; set; }
public string bookingCode { get; set; }
public int bookingCodeCount { get; set; }
public string marriedSegmentGroup { get; set; }
public List<Leg> leg { get; set; }
public int connectionDuration { get; set; }
}
public class Slouse
{
public string kind { get; set; }
public int duration { get; set; }
public List<Segment> segment { get; set; }
}
public class Fare
{
public string kind { get; set; }
public string id { get; set; }
public string carrier { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string basisCode { get; set; }
}
public class BagDescriptor
{
public string kind { get; set; }
public string commercialName { get; set; }
public int count { get; set; }
public string subcode { get; set; }
public List<string> description { get; set; }
}
public class FreeBaggageOption
{
public string kind { get; set; }
public List<BagDescriptor> bagDescriptor { get; set; }
public int pieces { get; set; }
}
public class SegmentPricing
{
public string kind { get; set; }
public string fareId { get; set; }
public string segmentId { get; set; }
public List<FreeBaggageOption> freeBaggageOption { get; set; }
}
public class Passengers
{
public string kind { get; set; }
public int adultCount { get; set; }
}
public class Tax2
{
public string kind { get; set; }
public string id { get; set; }
public string chargeType { get; set; }
public string code { get; set; }
public string country { get; set; }
public string salePrice { get; set; }
}
public class Pricing
{
public string kind { get; set; }
public List<Fare> fare { get; set; }
public List<SegmentPricing> segmentPricing { get; set; }
public string baseFareTotal { get; set; }
public string saleFareTotal { get; set; }
public string saleTaxTotal { get; set; }
public string saleTotal { get; set; }
public Passengers passengers { get; set; }
public List<Tax2> tax { get; set; }
public string fareCalculation { get; set; }
public string latestTicketingTime { get; set; }
public string ptc { get; set; }
}
public class TripOption
{
public string kind { get; set; }
public string saleTotal { get; set; }
public string id { get; set; }
public List<Slouse> slice { get; set; }
public List<Pricing> pricing { get; set; }
}
public class Trips
{
public string kind { get; set; }
public string requestId { get; set; }
public Data data { get; set; }
public List<TripOption> tripOption { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public Trips trips { get; set; }
}
Code :
var obj0 = JsonConvert.DeserializeObject<RootObject>(responsedata);
Here I got only Trip class element . I want the Leg and Flight class element.
If you want to find information for a specific leg, you need to use Linq to traverse the tree. For example, if you just know the leg id, you could do something like this:
var allLegs = obj0.trips.tripOption.SelectMany(to => to.slice.SelectMany(sl => sl.segment.Select(sg => sg.leg)));
var leg = allLegs.FirstOrDefault(l => l.id == "yourId");
The query for retrieving a flight would be similar. You could also filter by tripOption id to get a specific tripOption and then retrieve flights or legs that are associated with it.

Categories