C# Entity Foreign Key to List Array - c#

I have a class PromoCard and List<PromoCard> PromoCards. Is it possible to map element of List array in Entity Model?
This is my List:
public static List<PromoCard> PromoCards = new List<PromoCard>
{
new PromoCard()
{
Id = 1,
Crystal = 4500,
Price = 100
},
new PromoCard()
{
Id = 2,
Crystal = 24000,
Price = 500
},
new PromoCard()
{
Id = 3,
Crystal = 50000,
Price = 1000
},
};
public class PromoCard
{
[Key]
public int Id { get; set; }
public int Crystal { get; set; }
public int Price { get; set; }
}
And this is my model:
public class BonusCard
{
[Key]
public int Id { get; set; }
public string User_id { get; set; }
[ForeignKey("User_id")]
public virtual ApplicationUser User { get; set; }
public int PromoCard_id { get; set; }
// is there way to link
[ForeignKey("PromoCard_id")]
public virtual PromoCard PromoCard { get; set; }
}

All I had to was change the getter of PromoCard property and put NotMapped Annotation on it
public class BonusCard
{
[Key]
public int Id { get; set; }
public string User_id { get; set; }
[ForeignKey("User_id")]
public virtual ApplicationUser User { get; set; }
public string Code { get; set; }
public DateTime CreationDate { get; set; } = (DateTime)SqlDateTime.MinValue;
public DateTime UsageDate { get; set; } = (DateTime)SqlDateTime.MinValue;
public int? Player_id { get; set; } = null;
[ForeignKey("Player_id")]
public virtual Player Player { get; set; }
public int PromoCard_id { get; set; }
[NotMapped]
public PromoCard PromoCard { get { return PromoCards[PromoCard_id]; } set { } }
}

Related

AutoMapper not mapping child list of objects

I have a parent object(brand) with list of 5 child object(campaign):
Brand response = await _brandRepository.GetAsync(request.Id);
//other properties mapped fine, but Campaing is null..
var result = _mapper.Map<BrandDto>(response);
return result;
I have these definations for mapping:
CreateMap<Domain.Entity.Campaign, CampaignDto>();
CreateMap<Domain.Entity.Brand, BrandDto>();
objects:
public class BrandDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<CampaignDto> Campaing { get; set; }
}
public class CampaignDto
{
public int Id { get; set; }
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public CampaignDto ParentCampaign { get; set; }
public BrandDto Brand { get; set; }
}
entities:
public class Brand : SqlEntityBase
{
public string Name { get; set; }
public List<Campaign> Campaign { get; set; } = new List<Campaign>();
}
public class Campaign : SqlEntityBase
{
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public Guid ImpressionId { get; set; }
public string Name { get; set; }
public EntryStatus Status { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime CreatedOn { get; set; }
public Brand Brand { get; set; }
public Campaign ParentCampaign { get; set; }
}
If I map child object manually it works fine, but its not cool
how can I make this proper way?

Reference to other entity property

I have two models in the database in a C# project looking like this:
public Company
{
{other props... }
public string Account{ get; set; }
// This is the prop I want from the Account with Account.Account == Company.Account
public int BudgetEntryType { get; set; }
}
public Account
{
public string Account{ get; set; }
public int BudgetEntryType { get; set; }
}
The value of Company.BudgetEntryType is defined in Account.BudgetEntryType, and is dependent on the value of Company.BudgetEntryType.
Is there a way of doing so? So the Company.BudgetEntryType is a reference to the Account.BudgetEntryType.
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Account
{
public int Id { get; set; }
public int BudgetEntryType { get; set; }
public int CompanyId { get; set; }
public Company Company { get; set; }
}
public class ApplicationContext : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Account> Accounts { get; set; }
//other code
}
//-----using
Company company = new Company { Name = "Samsung" };
db.Companies.Add(company);
Account account = new Account { Company = company, BudgetEntryType = 2 };
db.Accounts.Add(account);
db.SaveChanges();

How to fix SqlException: Invalid column name

I'm using EF code first migrations in MVC5 with SQL Server.
I created a post method, I'm posting DTO data from the client and its all fine i believe, but when i try to save the data to the db i get this invalid column name exception on a foreign key property.
This is the first time i actually counter this error. I checked other questions and most answers were related to the [ForeignKey] data annotation but i think i implemented it the right way
This is the Model
public class ServiceProvider
{
public Guid Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public double YearsOfExperiance { get; set; }
public double AverageRank { get; set; }
public string Nationality { get; set; }
public ICollection<JobImage> JobImages { get; set; }
public ICollection<Review> Reviews { get; set; }
public ICollection<Rank> Ranks { get; set; }
public bool Active { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
public Category Category { get; set; }
public bool Approved { get; set; }
}
This is the controller ActionResult method
[HttpPost]
public ActionResult AddServiceProvider(ServiceProviderDTO serviceProvider)
{
bool isInDb = _context.ServiceProviders.Any(s => s.Name == serviceProvider.Name) ? true : false;
//var serviceProviderInDb = _context.ServiceProviders.Where(s => s.Name == serviceProvider.Name).FirstOrDefault();
var newServiceProvider = new ServiceProvider();
if (isInDb == false)
{
newServiceProvider = new ServiceProvider
{
Id = Guid.NewGuid(),
Name = serviceProvider.Name,
PhoneNumber = serviceProvider.PhoneNumber,
YearsOfExperiance = serviceProvider.YearsOfExperiance,
Nationality = serviceProvider.Nationality,
CategoryId = serviceProvider.CategoryId,
Active = true,
Approved = serviceProvider.Approved == null ? false : serviceProvider.Approved.Value
};
_context.ServiceProviders.Add(newServiceProvider);
_context.SaveChanges();
}
return RedirectToAction("Index", "Home");
}
The error occurs on _context.SaveChanges();
It states that CategoryId is an invalid column name
This is not the first time that i use code first migrations and i never came across this error before so i really have no idea why this happens!
I would have the model like this.
The ForeignKey attribute belong to the Category property
public class ServiceProvider
{
public Guid Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public double YearsOfExperiance { get; set; }
public double AverageRank { get; set; }
public string Nationality { get; set; }
public ICollection<JobImage> JobImages { get; set; }
public ICollection<Review> Reviews { get; set; }
public ICollection<Rank> Ranks { get; set; }
public bool Active { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
public bool Approved { get; set; }
}
you need delete this property public int CategoryId { get; set; }
your property public Category Category { get; set; } is the ForeignKey and add the DataAnnotations [ForeignKey("CategoryId")]
it would look like this
public class ServiceProvider
{
public Guid Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public double YearsOfExperiance { get; set; }
public double AverageRank { get; set; }
public string Nationality { get; set; }
public ICollection<JobImage> JobImages { get; set; }
public ICollection<Review> Reviews { get; set; }
public ICollection<Rank> Ranks { get; set; }
public bool Active { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
public Category Category { get; set; }
public bool Approved { get; set; }
}

How to join tables using LINQ and navigation properties

Previous question link
Consider to my previous question (I put a link to it) I need to get some different information.
Here is a DB structure I only added navigation property
public virtual ICollection<Accident> Accidents { get; set; }
to Transport class
public class Person
{
[Key]
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Transport
{
[Key]
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
public virtual ICollection<Accident> Accidents { get; set; }
}
public class Accident
{
[Key]
public int AccsidentID { get; set; }
public DateTime AccidentDate { get; set; }
public int TransportID { get; set; }
[ForeignKey("TransportID")]
public virtual Transport Transport { get; set; }
public int PersonID { get; set; }
[ForeignKey("PersonID")]
public virtual Person Person { get; set; }
}
public class AccsidentObject
{
[Key]
public int AccidentID { get; set; }
public DateTime AccidentDate { get; set; }
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
If I want to get all accidents I use
var accidents = DBContext.Accidents.Select( a => new AccidentObject
{
AccidentID = a.AccidentId,
AccidentDate
TransportID
Model
Brand = a.Transport.Brand,
PersonID = a.Person.PersonID,
FirstName
LastName
});
What would be a code if I would like to select TransportObject with added specific Accident data
public class TransportObject
{
[Key]
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
public int AccidentID { get; set; }
public DateTime AccidentDate { get; set; }
}
Use this code
var transports = DBContext.Transports
.SelectMany(
x => x.Accidents,
(t, a) => new TransportObject
{
TransportID = t.TransportID,
Model = t.Model,
Brand = t.Brand,
AccidentID = a.AccidentId,
AccidentDate = a.AccidentDate
}
);
More about select many in MSDN.

Adding an single entity multiple relationships

I have an entity and I'm trying to add it to a collection in two different entities.
What I want to achieve is something like
[1] => DomainUser { name = "bob" }
DomainGroup.Users = [ 1 ]
LocalGroup.Users = [ 1 ]
When I try to save changes, however, I get Multiplicity constraint violated. The role 'DomainGroup_Users_Source' of the relationship 'Server.DomainTools.Models.DomainGroup_Users' has multiplicity 1 or 0..1.
Here's my entities:
This is where I feel my issues lies: DomainUser
public class DomainUser
{
public string Name { get; set; }
public int Id { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
public int AdminCount { get; set; }
public int PwdLastSet { get; set; }
public string AdsPath { get; set; }
public int LastLogon { get; set; }
public int LastLogoff { get; set; }
public int LockoutTime { get; set; }
public int AccountExpires { get; set; }
public int BadPwdCount { get; set; }
public int LogonCount { get; set; }
}
And here are the two entities that I'm trying to add DomainUser to: DomainGroup and LocalGroup
public class DomainGroup
{
public string Name { get; set; }
public List<DomainUser> Users { get; set; }
public List<DomainGroup> Groups { get; set; }
public string DistinguishedName { get; set; }
public int Id { get; set; }
public DomainGroup()
{
Users = new List<DomainUser>();
Groups = new List<DomainGroup>();
}
}
public class LocalGroup
{
public string Name { get; set; }
public int Id { get; set; }
public string DisplayName { get; set; }
public string Comment { get; set; }
public List<LocalUser> LocalUsers { get; set; }
public List<DomainUser> DomainUsers { get; set; }
public List<DomainGroup> DomainGroups { get; set; }
public List<LocalGroup> LocalGroups { get; set; }
public LocalGroup()
{
LocalUsers = new List<LocalUser>();
LocalGroups = new List<LocalGroup>();
DomainUsers = new List<DomainUser>();
DomainGroups = new List<DomainGroup>();
}
}

Categories

Resources