Entity Framework 1:1 relationship Code First - ef-code-first

I'm struggling here. I've tried through data annotations and via the Fluent API and still not working correctly. Desperate for help now. Basically, I have two tables. A Company table and an Address Table. A company must have a head office address (which should live in the Address Table) and an Address must have a Company which is belongs too. I'm really struggling to set this up correctly.
I'll put the Code First Entities then show what I have already got.
[Table("Address")]
public class Address
{
[Key]
public long AddressId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Address4 { get; set; }
public string Address5 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Country { get; set; }
public string PostCode { get; set; }
public virtual Company Company { get; set; }
public DateTime? RemovedDate { get; set; }
public long? RemovedBy { get; set; }
}
[Table("Company")]
public class Company
{
[Key ]
public long CompanyId { get; set; }
public string Name { get; set; }
public string WebsiteUrl { get; set; }
public virtual Address Address { get; set; }
public User LeadUser { get; set; }
public DateTime ActiveSince { get; set; }
public DateTime? ActiveTill { get; set; }
public string VatRegistration { get; set; }
public string LicenseKey { get; set; }
public LicenseStatus LicenseStatus { get; set; }
public bool CanAgreementBeExtended { get; set; }
public string BillingEmail { get; set; }
public string PhoneNumber { get; set; }
public string MobileNumber { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<LicenseHistory> LicenseHistories { get; set; }
}
//Seeded data inserted as follows
var testCompany = new Company
{
ActiveSince = DateTime.UtcNow,
Name = "Test Company",
LeadUser = adminUser,
DateCreated = DateTime.UtcNow,
DateUpdated = DateTime.UtcNow,
BillingEmail = "admin#test.co.uk",
CanAgreementBeExtended = true,
LicenseStatus = LicenseStatus.PendingAgreement,
MobileNumber = "1234567890",
PhoneNumber = "1234567890",
VatRegistration = "1234567890"
};
context.Companies.AddOrUpdate(u => u.Name, testCompany);
var testAddress = new Address
{
Address1 = "Test Ltd",
Address2 = "1 Test Gardens",
Address3 = "Test Heath",
Address4 = string.Empty,
Address5 = string.Empty,
County = "Test",
Town = "Test",
Country = "United Kingdom",
PostCode = "TE5 T11",
Company = testCompany
};
context.Addresses.AddOrUpdate(u => new { u.AddressId }, testAddress);
testCompany.Address = testAddress;
context.Companies.AddOrUpdate(u => u.Name, testCompany);
//Fluent API set up as follows in the OnModelCreating
modelBuilder.Entity<Address>()
.HasRequired(ad => ad.Company)
.WithOptional(s => s.Address);
Can anyone spot what I'm doing wrong? I've been playing round with different combinations for the past few days and it just doesn't work. I just keep getting errors, the latest error based on the code above is...
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'AddressId'.
Any ideas please?

You can't have a true one to one in SQL Server (see How do I create a real one-to-one relationship in SQL Server), but there is a workaround in EF where you make the primary key of the second entity also a foreign key:
// [Table("Company")] -- not needed unless different
public class Company
{
// [Key ] -- will be key by convention
public long CompanyId { get; set; }
...
public virtual Address Address { get; set; }
}
public class Address
{
[Key, ForeignKey("Company")]
public long AddressId { get; set; }
public string Address1 { get; set; }
...
public virtual Company Company { get; set; }
}
You can also do it with fluent code like:
modelBuilder.Entity<Company>()
.HasRequired(t => t.Address)
.WithRequiredPrincipal(t => t.Company);

Related

Translate LINQ to LAMBDA Entity Framework Core using INCLUDE (NOT JOIN)

How to call multiple entities using Include method (not Join method) in Entity Framework Core? I am trying to translate this LINQ query to EF Core 5 syntax, but I do not know how to call multiple entities and join them together using include method.
var reservations = from reservation in _dbContext.Reservations
join customer in _dbContext.Users on reservation.UserId equals customer.Id
join movie in _dbContext.Movies on reservation.MovieId equals movie.Id
select new
{
Id = reservation.Id,
ReservationTime = reservation.ReservationTime,
CustomerName = customer.Id,
MovieName = movie.Name
};
I tried using multiple include and select method, but do not know how to call multiple entities and join
Here are my models
public class Reservation
{
public int Id { get; set; }
public int Qty { get; set; }
public double Price { get; set; }
public string Phone { get; set; }
public DateTime ReservationTime { get; set; }
public int MovieId { get; set; }
public int UserId { get; set; }
}
public class Movie
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Language { get; set; }
public string Duration { get; set; }
public DateTime PlayingDate { get; set; }
public DateTime PlayingTime { get; set; }
public double TicketPrice { get; set; }
public double Rating { get; set; }
public string Genre { get; set; }
public string TrailorUrl { get; set; }
public string ImageUrl { get; set; }
[NotMapped]
public IFormFile Image { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}
Controller code:
var reservations = _dbContext.Reservations
.Include(r => r.Id)
.Include(c => c.User)
.Select(x => new { x.Id, x.ReservationTime, x.User, x.User.Name });
If add to Reservation navigation properties Movie and User, your query can be simplified. Include cannot be used with Select together, it is ignored by EF translator.
var reservations = _dbContext.Reservations
.Select(r => new
{
Id = r.Id,
ReservationTime = r.ReservationTime,
CustomerName = r.User.Id,
MovieName = r.Movie.Name
});

Deserialize json without root object and 1 array ASP.NET MVC

I'm building a web application that's using a third parties API and I receive the json below
{
"CompanyID": 14585,
"CompanyName": "The Morgan Group Daytona, LLC",
"BillingAddressLine": "100 S Beach St #200",
"BillingAddressCity": "Daytona Beach",
"BillingAddressState": "Fl",
"BillingAddressPostCode": "32114",
"BillingCountryCode": "US",
"BillingAddress": "100 S Beach St #200\r\nDaytona Beach Fl 32114\r\nUNITED STATES",
"Phone": null,
"Fax": null,
"website": null,
"TaxNumber": null,
"Comments": null,
"CurrencyCode": "USD",
"DefaultTradingTermIDFK": 15,
"DateCreated": "2020-09-04T18:25:02",
"DateUpdated": "2020-09-04T18:25:02",
"Contacts": [
{
"ContactID": 13781,
"CompanyIDFK": 14585,
"CompanyName": null,
"Firstname": "Test",
"Lastname": "User",
"Email": "test#test.com",
"Phone": null,
"Mobile": "4075551234",
"PositionTitle": "Test Title",
"TimeZone": "Eastern Standard Time",
"DateCreated": "2020-09-07T02:21:10",
"DateUpdated": "2020-09-07T02:21:10"
}
]
}
All of the other json responses for the other API calls also do not have root objects. The goal is to use razor to display this information on the view. Whats the most efficient way to do so?
So far I've created this class file
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
but now i'm stuck on trying to figure out how to deserialize something like this? Whats the easiest way to do this. I can't seem to find any other post that matches this same set of circumstances.
When you get a blob of JSON, you can speed things up by going to https://json2csharp.com/ and have it convert it in to classes. For example, that blob returns this:
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string website { get; set; }
public string TaxNumber { get; set; }
public string Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
The classes it returns will sometimes have some small issues, for example, since your blob had a lot of null properties, it just converted them to object. I changed them to string.
Then you simply use Newtonsoft.Json to convert it:
using(var s = File.OpenRead(#"c:\users\andy\desktop\test.json"))
using(var sr = new StreamReader(s))
using(var jtr = new JsonTextReader(sr))
{
var obj = new JsonSerializer().Deserialize<Root>(jtr);
}
And you are finished:
ETA
You posted your code on getting this data and noticed you are using WebRequest. Just a heads up that WebRequest is legacy and you should be using HttpClient. This is how you download/deserialize with HttpClient:
private static readonly HttpClient _httpClient = new HttpClient();
private static async Task<Root> GetStuffFromThereAsync(string token)
{
using(var req = new HttpRequestMessage(HttpMethod.Get,
new Uri("https://www.example.com")))
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var resp = await _httpClient.SendAsync(req))
{
resp.EnsureSuccessStatusCode();
using (var s = await resp.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(s))
using (var jtr = new JsonTextReader(sr))
{
return new JsonSerializer().Deserialize<Root>(jtr);
}
}
}
}
If it is still returning null, then there is a chance your models don't match.
You need to use the below the line with class I have mentioned :
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>("This is the your JSON string");
Class
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}

How to check completed orders when user is logged in?

Currently I create a shop and I use ASP Identity razor pages to login, logout and registration. I have default IdentityUser. I have also ASPNetUsers table and I want reference row UserId to my other table Orders. My main purpose to achieve is when user logg in, he can check his completed orders from database. I know how to use LINQ to get order from database, but I didn't know how to connect that with Identity. I also use Session for adding item to cart if it is important.
public class AppDbContext : IdentityDbContext<IdentityUser>
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Game> Games { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<SubGenre> SubGenres { get; set; }
public DbSet<CartItem> CartItems { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<ShipAddress> ShipAddresses { get; set; }
}
public class ShipAddress
{
[BindNever]
public int ShipAddressId { get; set; }
public List<Order> Orders { get; set; }
[Required(ErrorMessage = "Wpisz swoje imię!")]
[StringLength(50)]
[Display(Name = "Imię:")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Wpisz swoje nazwisko!")]
[StringLength(50)]
[Display(Name = "Nazwisko:")]
public string LastName { get; set; }
[Required(ErrorMessage = "Wpisz nazwę ulicy!")]
[StringLength(50)]
[Display(Name = "Ulica:")]
public string Address1 { get; set; }
[Required(ErrorMessage = "Wpisz numer domu/lokalu!")]
[StringLength(50)]
[Display(Name = "Nr domu/lokalu:")]
public string Address2 { get; set; }
[Required(ErrorMessage = "Wpisz kod pocztowy!")]
[StringLength(6)]
[Display(Name = "Kod pocztowy:")]
public string ZipCode { get; set; }
[Required(ErrorMessage = "Wpisz miejscowość!")]
[StringLength(50)]
[Display(Name = "Miejscowość:")]
public string City { get; set; }
[Required(ErrorMessage = "Wpisz numer kontaktowy!")]
[StringLength(9)]
[Display(Name = "Nr telefonu:")]
public string PhoneNumber { get; set; }
[BindNever]
public decimal OrderTotal { get; set; }
[BindNever]
public DateTime OrderPlaced { get; set; }
public IdentityUser User { get; set; }
public int IdentityUserId { get; set; }
}
Current Login User
var userID = User.Identity.GetUserId();
This will give your current login user id then you can apply linq for based on this id with and condition of completed order you store in table
Use User's Identity which u logged in by using
string userID = User.Identity.GetUserId();

ServiceStack, OrmLite Issue Saving Related Entities

I've searched for a while looking for a solution to this problem and haven't found anything.
I'm trying to POST a Client DTO and it's related Contacts DTOs to my ServiceStack web service but I'm getting an error. I've followed along with the OrmLite tests located here.
My DTOs:
public partial class Client {
[AutoIncrement]
public int ID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public decimal? Latitude { get; set; }
public decimal? Longitude { get; set; }
public string HomePhoneAreaCode { get; set; }
public string HomePhoneExchange { get; set; }
public string HomePhoneNumber { get; set; }
public string HomeFaxAreaCode { get; set; }
public string HomeFaxExchange { get; set; }
public string HomeFaxNumber { get; set; }
public string KeyNumber { get; set; }
public string AlarmCode { get; set; }
public string GarageDoorCode { get; set; }
public string MyAPCUsername { get; set; }
public string MyAPCPassword { get; set; }
public bool IsActive { get; set; }
public string Notes { get; set; }
[Reference]
public List<Contact> Contacts { get; set; }
}
public partial class Contact {
[AutoIncrement]
public int ID { get; set; }
public int ClientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string WorkPhoneAreaCode { get; set; }
public string WorkPhoneExchange { get; set; }
public string WorkPhoneNumber { get; set; }
public string MobilePhoneAreaCode { get; set; }
public string MobilePhoneExchange { get; set; }
public string MobilePhoneNumber { get; set; }
public bool CanSMS { get; set; }
public string PersonalEmail { get; set; }
public string WorkEmail { get; set; }
public string AlternateEmail { get; set; }
public int Ordinal { get; set; }
[Reference]
public Client Client { get; set; }
}
In my Service:
public int Post(Client client) {
Db.Save(client, references: true);
return client.ID;
}
And my test code:
var newClient = new Client {
Street = "1234 Any Avenue",
City = "Gorham",
State = "ME",
ZipCode = "22222",
HomePhoneAreaCode = "123",
HomePhoneExchange = "456",
HomePhoneNumber = "7890",
HomeFaxAreaCode = "098",
HomeFaxExchange = "765",
HomeFaxNumber = "4321",
KeyNumber = "99",
AlarmCode = "1234",
GarageDoorCode = "abcd",
IsActive = true,
Notes = "These are the notes for the new client.",
Contacts = new List<Contact>() {
new Contact { FirstName = "John", LastName = "Doe", PersonalEmail = "john.doe#gmail.com", CanSMS = true, Ordinal = 1 },
new Contact { FirstName = "Jane", LastName = "Smith", PersonalEmail = "jane.smith#gmail.com", CanSMS = false, Ordinal = 2 }
},
};
// POST entity
int newClientID = serviceClient.Post<int>(newClient);
The last line produces the error -
WebServiceException, message "Cant find 'ClientId' Property on Type 'Contact'"
I've tried different combinations of the Reference, References, and ForeignKey attributes to no avail.
Any help would be appreciated.
Thanks,
Jay

EF code first update is not working for one to many relationship

The EF code first update is not working for one to many relationship
I have 2 entities
// Save
public class Person
{
public int Id { get; set; }
public string Name{ get; set; }
public virtual List<Email> Emails { get; set; }
}
public class Email
{
public int Id { get; set; }
public int PersonId { get; set; }
public virtual Person person { get; set; }
public string EmailAddress { get; set; }
}
EFContext context = new EFContext();
Person person;
Email email;
person = new Person();
person.Name = "Rocky";
person.Emails = new List<Email>();
email = new Email { EmailAddress = "rocky#frostbitefalls.com" };
person.Emails.Add(email);
email = new Email { EmailAddress = "rocky#squirrel.com" };
person.Emails.Add(email);
context.People.Add(person);
context.SaveChanges();
// Update
person = new Person();
person.Id=1;
person.Name = "Rocky Altered";
person.Emails = new List<Email>();
email = new Email {Id=1, EmailAddress = "Altered_rocky#frostbitefalls.com" };
person.Emails.Add(email);
email = new Email {Id=2, EmailAddress = "Altered_rocky#squirrel.com" };
person.Emails.Add(email);
UpdatePerson(person);
public bool UpdatePerson(Person entity)
{
var updatePerson = GetPersonById(entity.Id);
updatePerson.Name=entity.Name;
updatePerson.Emails=entity.Emails;
DataContext.Entry<Person>(updatePerson).State = EntityState.Modified;
DataContext.SaveChanges();
DataContext.Entry<Person>(updatePerson).Reload();
}
The person with 2 email addresses are saving properly but while updating the email address of the inserted person is not working.
You should do something like this:
public class Person
{
public int Id { get; set; }
public string Name{ get; set; }
public List<Email> Emails { get; set; }
}
public class Email
{
public int Id { get; set; } //This will generate PKey.
public virtual Person person { get; set; } //This will create the FKey.
public string EmailAddress { get; set; }
}
The problem you're having is that you need to apply a ForeignKeyAttribute to any FK you explicitly include:
public class Person
{
public int Id { get; set; }
public string Name{ get; set; }
public virtual List<Email> Emails { get; set; }
}
public class Email
{
public int Id { get; set; }
[ForeignKey("Person")]
public int PersonId { get; set; }
public virtual Person Person { get; set; }
public string EmailAddress { get; set; }
}
By applying that attribute you tell EF Migrations to use "PersonId" as the FK column name for the "Person" relationship. The rest should work as-is.

Resources