Razor display date MVC - asp.net-mvc

I have html as
#Html.EditorFor(model => model.DateOfBirth})
and property as
[DataType(DataType.Date, ErrorMessage = "Invaild date.")]
[Display(Name = "Date of birth")]
public DateTime DateOfBirth { get; set; }
controller code is as
public ActionResult Edit(int id)
{
var member = (MembersViewModel)_db.Members.Single(f => f.Id == id);
return View(member);
}
Model Is as
public class MembersViewModel
{
public int Id { get; set; }
public int GymId { get; set; }
public Gym Gym { get; set; }
public ICollection<Gym> Gyms { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public Address ShippingAddress { get; set; }
public Address BillingAddress { get; set; }
public string PhoneNumber { get; set; }
public string EmailAddress { get; set; }
[DataType(DataType.Date, ErrorMessage = "Invaild date.")]
[Display(Name = "Date of birth")]
public DateTime DateOfBirth { get; set; }
public static implicit operator MembersViewModel(Member member)
{
return new MembersViewModel
{
BillingAddress = member.BillingAddress,
FirstName = member.FirstName,
Gyms = member.Gyms,
Id = member.Id,
LastName = member.LastName,
MiddleName = member.MiddleName,
ShippingAddress = member.ShippingAddress,
DateOfBirth = member.DateOfBirth
};
}
public static explicit operator Member(MembersViewModel member)
{
return new Member
{
BillingAddress = member.BillingAddress,
FirstName = member.FirstName,
Gyms = member.Gyms,
Id = member.Id,
LastName = member.LastName,
MiddleName = member.MiddleName,
ShippingAddress = member.ShippingAddress,
DateOfBirth = member.DateOfBirth
};
}
}
It will allow me to select date from calender. And yes also save it in a database. But when I want to populate the saved date, then text box remains empty. I don't know why, even I get saved date and also pass to my model. Does anyone have any idea?

Yes I have solve this, not sure is it right or wrong but Work for me
#Html.EditorFor(model => model.DateOfBirth)
#Html.ValidationMessageFor(model => model.DateOfBirth)
#Html.Hidden("hiddenFieldDateofBirth", Model.DateOfBirth.ToString("yyyy-MM-dd"))
<script>
$("#DateOfBirth").val($("#hiddenFieldDateofBirth").val());
</script>

Related

Problem Insterting Multiple data on 2 tables

i am having problem on inserting multiple data in two tables.
Here is my code
Context Class
var userId = Convert.ToUInt32(user.Single(logon => logon.Type == CustomClaimTypes.UserId).Value);
/*Create access table for insert*/
var modules = p.Select(collection => new Accountcollection
{
AccountId = userId,
Amount = collection.Amount,
CashSource = collection.CashSource,
CollectionDate = collection.CollectionDate,
CreatedDatetime = DateTime.Now,
UpdatedDatetime = DateTime.Now,
}).ToList();
_context.Accountcollection.AddRange(modules);
var calendar_event = p.Select(collection => new Accountcalendarevents
{
AccountId = userId,
Subject = collection.CashSource,
Description = collection.CashSource,
Start = collection.CollectionDate,
End = collection.CollectionDate,
ThemeColor = "blue",
Isfullday = true,
Status = "1",
CreatedBy = userId,
CreatedDatetime = DateTime.Now,
UpdatedBy = userId,
UpdatedDatetime = DateTime.Now
}).ToList();
_context.Accountcalendarevents.AddRange(calendar_event);
_context.SaveChanges();
}
This is my collection model
public partial class Accountcollection
{
[Key]
public long Id { get; set; }
public long AccountId { get; set; }
public double? Amount { get; set; }
public string CashSource { get; set; }
public DateTime CollectionDate { get; set; }
public DateTime? CreatedDatetime { get; set; }
public DateTime? UpdatedDatetime { get; set; }
//public Accountcalendarevents Accountcalendarevents { get; set; }
public virtual Accountmaster Account { get; set; }
}
And this is my Caldendar Manager Events Model
public class Accountcalendarevents
{
[Key]
public long Id { get; set; }
public long AccountId { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public string ThemeColor { get; set; }
public bool Isfullday { get; set; }
public string Status { get; set; }
public long CreatedBy { get; set; }
public DateTime CreatedDatetime { get; set; }
public long UpdatedBy { get; set; }
public DateTime UpdatedDatetime { get; set; }
}
The problem is when I insert only 1 data in works fine but if I try to insert 2 or more, i am getting this kind of exception
Exception i got
But, when I commented
var calendar_event = p.Select(collection => new Accountcalendarevents
{
//AccountId = userId, <-- when I comment this line
Subject = collection.CashSource,
Description = collection.CashSource,
Start = collection.CollectionDate,
End = collection.CollectionDate,
ThemeColor = "blue",
Isfullday = true,
Status = "1",
CreatedBy = userId,
CreatedDatetime = DateTime.Now,
UpdatedBy = userId,
UpdatedDatetime = DateTime.Now
}).ToList();
it works properly on multiple data insertion.
Hope you helped me with this. Thank you!

Many to many relationship in MVC - write to a table with foreign keys

In model I have 3 tables in relation to many many.
public class Order
{
[Key]
public int IdOrder { get; set; }
public string UserId { get; set; }
public virtual User User { get; set; }
public int IdOrderAttachment { get; set; }
public virtual OrderAttachment OrderAttachment { get; set; }
public virtual ICollection<Employee> Employee { get; set; }
[Required(ErrorMessage = "Specify the date of order acceptance")]
[Display(Name = "Date of acceptance of the order")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTimeDateOfAcceptance { get; set; }
[Display(Name = "Date of completion planning")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? DateOfCompletionPlanning { get; set; }
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }
[Required(ErrorMessage = "Enter the subject")]
[MaxLength(200, ErrorMessage = "Name max 200 characters")]
[Display(Name = "Subject")]
public string Subject { get; set; }
public virtual ICollection<OrderPosition> OrderPosition{ get; set; }
}
public class OrderPosition
{
[Key]
public int IdOrderPosition { get; set; }
public int IdOrder { get; set; }
public int IdPosition { get; set; }
public virtual Order Order { get; set; }
public virtual Position Position { get; set; }
}
public class Position
{
[Key]
public int IdPosition { get; set; }
[Column(TypeName = "nvarchar(MAX)")]
[Display(Name = "Description")]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Description { get; set; }
public virtual ICollection<OrderPosition> OrderPosition { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrder(HttpPostedFileBase file, DataOrderUserViewModel viewModel)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
string path = "/Content/Layout/CompanyFile";
if (!Directory.Exists(HttpContext.Server.MapPath(path)))
{
Directory.CreateDirectory(HttpContext.Server.MapPath(path));
}
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Path.Combine(HttpContext.Server.MapPath(path), filename));
viewModel.NameFile = path+ "/" + filename;
//var nameFile = Path.GetFileName(file.FileName);
//var path = Path.Combine(Server.MapPath("/Content/Layout/CompanyFile"), nameFile);
//file.SaveAs(path);
}
var order = new Order()
{
DateTimeDateOfAcceptance = viewModel.DateTimeDateOfAcceptance,
Subject= viewModel.Subject,
UserId = userId
};
var position = new Position ()
{
Description = viewModel.Description
};
var orderAttachment = new OrderAttachment ()
{
NameFile= viewModel.NameFile,
Description = viewModel.Description2
};
db.Order.Add(order);
db.Position.Add(position);
db.OrderAttachment.Add(orderAttachment);
db.SaveChanges();
}
return RedirectToAction("Index", "Administration");
}
My question is how to write data to the OrderPosition table.
I understand that I should first write data in the Order and Position table.
Then, having two keys from these arrays, I should read them and send them to the OrderPosition as external keys where they will be saved.
What should a record of these instructions look like?
Do I need to define the following relationships in my case?
modelBuilder.Entity<OrderPosition>()
.HasKey(c => new { c.IdOrder , c.IdPosition });
modelBuilder.Entity<Order>()
.HasMany(c => c.Subject )
.WithRequired()
.HasForeignKey(c => c.IdOrder );
modelBuilder.Entity<Position>()
.HasMany(c => c.Description )
.WithRequired()
.HasForeignKey(c => c.IdPosition );

DropDownListFor selection not being saved

I am new to MVC. I am using a DropDownListFor to display a list of company names and, based on the selection made, filling in other Customer fields. The customer fields are being populated fine, but when I attempt to POST the record, I get a validation error "Company name is required", even though the company name has been selected in the DropDownListFor. Here is the ViewModel:
namespace CMSUsersAndRoles.Models
{
public class QuoteViewModel
{ [Key]
[Display(Name = "Quote Id")]
public int QuoteId { get; set; }
// Columns from Customer table
[Required(ErrorMessage = "Please select a company")]
[Display(Name = "Customer Id")]
public int? CustomerId { get; set; }
[Display(Name = "Sales Rep")]
public string SalesRep { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Company { get; set; }
[Display(Name = "Address 1")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[StringLength(10)]
[Display(Name = "Zip Code")]
[RegularExpression(#"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip Code")]
public string PostalCode { get; set; }
[Phone]
[Display(Name = "Work Phone")]
public string WorkPhone { get; set; }
[Phone]
[Display(Name = "Cell Phone")]
public string CellPhone { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(0, 100)]
public decimal? Discount { get; set; }
[Display(Name = "Payment Terms")]
public int? PaymentTerms { get; set; }
// Columns from QuoteDetail table
[Display(Name = "Quote Detail")]
public List<QuoteDetail> QuoteDetail { get; set; }
// Columns from Quote table
public decimal Subtotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Date")]
public DateTime? QuoteDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Good Until")]
public DateTime? GoodUntil { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Sent")]
public DateTime? QuoteSent { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Approved")]
public DateTime? DateApproved { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Ordered")]
public DateTime? DateOrdered { get; set; }
}
}
Here is the code from the View:
#Html.DropDownListFor(model => model.CustomerId, new SelectList(ViewBag.Customers, "CustomerId", "Company"), "---Select one---", new { htmlAttributes = new { #class = "company" } });
#Html.HiddenFor(model => model.Company)
#Html.ValidationMessageFor(model => model.Company, "", new { #class = "text-danger" })
Here is the Get:
public ActionResult Create()
{
QuoteViewModel qvm = new QuoteViewModel();
var customers = db.Customers.ToList();
ViewBag.Customers = customers;
return View(qvm);
}
And here is the code for the POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QuoteViewModel qvm)
{
if (ModelState.IsValid)
{
Quote quote1 = new Quote();
quote1.CustomerId = qvm.CustomerId;
...
customer.CustomerId = (int)qvm.CustomerId;
...
customer.Company = qvm.Company;
db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
var objContext = ((IObjectContextAdapter)db).ObjectContext;
// Get failed entry
var entry = ex.Entries.Single();
// Now call refresh on ObjectContext
objContext.Refresh(RefreshMode.ClientWins, entry.Entity);
}
return RedirectToAction("Index");
}
var customers = db.Customers.ToList();
ViewBag.Customers = customers;
return View(qvm);
}
What am I missing? Any help will be much appreciated.
I was not setting the value of the HiddenFor below. Thanks, #StephenMuecke.
#Html.HiddenFor(model => model.Company)

EF5 Migrations throwing error on simplemembership seed

Error:
No mapping exists from object type eTrail.Models.Global.Address to a known managed provider native type.
The code that is throwing the error:
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
Address = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}
My User.cs Model:
public class User : IAuditInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public Address UserAddress { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public ICollection<Role> Roles { get; set; }
public string ImageName { get; set; }
public User()
{
UserAddress = new Address();
Roles = new List<Role>();
}
}
The Address Model:
public class Address
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Street { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public string PhoneHome { get; set; }
public string PhoneCell { get; set; }
public string PhoneOther { get; set; }
public string FaxNumber { get; set; }
}
Any idea why I am getting this error? Both Model classes are in my DbContext class as DbSet and DbSet.
You used the wrong property name when you created the new user account. You used Address instead of UserAddress. Make the following change under the comment I added to the code.
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
//Changed Address to UserAddress
UserAddress = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}

EF Code First and Linq to Entities, How to populate nested objects in one go?

I know there are similar problems out there, this one is almost the same How to create and populate a nested ViewModel well but it does not solve my problem.
Im using EF Code First and LINQ to Entities. These are some of my entities
public class Application
{
public int ApplicationID { get; set; }
public int ApplicationTypeID { get; set; }
public int MembershipTypeID { get; set; }
public string MailTo { get; set; }
public DateTime ApplicationDate { get; set; }
public int PersonID { get; set; }
.......
public virtual Person Person { get; set; }
.......
public virtual PaymentType PaymentType { get; set; }
}
public class Person
{
public int PersonID { get; set; }
public int? OrganisationID { get; set; }
public int? HomeAddressID { get; set; }
public int? WorkAddressID { get; set; }
public string Title { get; set; }
public string Initials { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string JobTitle { get; set; }
public string Department { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string Email { get; set; }
public bool NoInhouseMail { get; set; }
public bool NoThirdPartyMail { get; set; }
public DateTime Created { get; set; }
public DateTime? Updated { get; set; }
public virtual Address HomeAddress { get; set; }
public virtual Address WorkAddress { get; set; }
public virtual Organisation Organisation { get; set; }
public virtual ICollection<PersonAttribute> PersonAttributes { get; set; }
public virtual ICollection<Email> Emails { get; set; }
}
{
public class Address
{
public int AddressID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Town { get; set; }
public string Region { get; set; }
public string Postcode { get; set; }
public string CountryCode { get; set; }
public DateTime Created { get; set; }
public DateTime? Updated { get; set; }
public virtual Country Country { get; set; }
}
And this is how they are mapped
public ApplicationEntityTypeConfiguration()
{
//Mapping
this.HasKey(ap => ap.ApplicationID);
this.Property(ap => ap.ApplicationID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(ap => ap.WorldPayID)
.HasColumnType("bigint");
this.Property(ap => ap.Processed)
.HasColumnType("smalldatetime");
this.Property(ap => ap.Exported)
.HasColumnType("smalldatetime");
//Relationships
this.HasRequired(ap => ap.MembershipType)
.WithMany()
.HasForeignKey(ap => ap.MembershipTypeID);
this.HasRequired(ap => ap.ApplicationType)
.WithMany()
.HasForeignKey(ap => ap.ApplicationTypeID);
this.HasOptional(ap => ap.WorldPayStatus)
.WithMany()
.HasForeignKey(ap => ap.WorldPayStatusCode);
this.HasRequired(ap => ap.PaymentType)
.WithMany()
.HasForeignKey(ap => ap.PaymentTypeID);
this.HasRequired(ap => ap.Person)
.WithMany()
.HasForeignKey(ap => ap.PersonID);
this.HasRequired(ap => ap.InvoiceAddress)
.WithMany()
.HasForeignKey(ap => ap.InvoiceAddressID);
}
}
public class PersonEntityTypeConfiguration : EntityTypeConfiguration<Person>
{
public PersonEntityTypeConfiguration()
{
this.HasKey(p => p.PersonID);
this.Property(p => p.PersonID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(p => p.Created)
.HasColumnType("smalldatetime");
this.Property(p => p.Updated)
.HasColumnType("smalldatetime");
//Relationships
this.HasRequired(p => p.Organisation)
.WithMany()
.HasForeignKey(p => p.OrganisationID);
this.HasRequired(p => p.HomeAddress)
.WithMany()
.HasForeignKey(p => p.HomeAddressID);
this.HasRequired(p => p.WorkAddress)
.WithMany()
.HasForeignKey(p => p.WorkAddressID);
}
}
public class AddressEntityTypeConfiguration : EntityTypeConfiguration<Address>
{
public AddressEntityTypeConfiguration()
{
this.HasKey(a => a.AddressID);
this.Property(a => a.AddressID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(a => a.Created)
.HasColumnType("smalldatetime");
this.Property(a => a.Updated)
.HasColumnType("smalldatetime");
//Relationships))))
this.HasRequired(a => a.Country)
.WithMany()
.HasForeignKey(a => a.CountryCode)
.WillCascadeOnDelete(false);
}
}
This is the structure of the classes I am trying to populate
public class OrganisationEmailMessageData
{
public string ApplicationType { get; set; }
public int ApplicationId { get; set; }
public string PaymentType { get; set; }
public string MembershipType { get; set; }
public double Price { get; set; }
public string FullName { get; set; }
public string JobTitle { get; set; }
public string Department { get; set; }
public string Organisation { get; set; }
public AddressEmailData HomeAddress { get; set; }
public AddressEmailData WorkAddress { get; set; }
public AddressEmailData InvoiceAddress { get; set; }
public string PublicArea { get; set; }
public string[] AreasOfInterest { get; set; }
}
public class AddressEmailData
{
public bool Selected { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Address4 { get; set; }
public string Town { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
This is the way I am trying to populate an object of type OrganisationEmailMessageData in one go,
using (var db = _databaseFactory.GetDatabase())
{
var messageData = (from a in db.Applications
where a.ApplicationID == applicationId
select new OrganisationEmailMessageData
{
ApplicationType = a.ApplicationType.EmailMessage,
ApplicationId = a.ApplicationID,
PaymentType = a.PaymentType.Type,
MembershipType = a.MembershipType.Type,
Price = a.MembershipType.Price,
FullName = a.Person.Title + " " + a.Person.Forename + " " + a.Person.Surname,
JobTitle = a.Person.JobTitle,
Department = a.Person.Department ?? string.Empty,
Organisation = a.Person.Organisation != null
? a.Person.Organisation.Name
: string.Empty,
HomeAddress = a.Person.HomeAddressID.HasValue
? ( from add in db.Addresses
where add.AddressID == a.Person.HomeAddressID.Value
select new AddressEmailData
{
Address1 = add.Address1,
Address2 = add.Address2,
Address3 = add.Address3,
Address4 = add.Address4,
Region = add.Region,
Town = add.Town,
PostalCode = add.Postcode,
Country = add.Country.Name
}).Single()
: null,
WorkAddress = a.Person.WorkAddressID.HasValue
? (from add in db.Addresses
where add.AddressID == a.Person.WorkAddressID.Value
select new AddressEmailData
{
Address1 = add.Address1,
Address2 = add.Address2,
Address3 = add.Address3,
Address4 = add.Address4,
Region = add.Region,
Town = add.Town,
PostalCode = add.Postcode,
Country = add.Country.Name
}).Single()
: null,
InvoiceAddress = (from add in db.Addresses
where add.AddressID == a.InvoiceAddressID
select new AddressEmailData
{
Address1 = add.Address1,
Address2 = add.Address2,
Address3 = add.Address3,
Address4 = add.Address4,
Region = add.Region,
Town = add.Town,
PostalCode = add.Postcode,
Country = add.Country.Name
}).Single(),
PublicArea = a.Person.PersonAttributes.Select(att => att.Attribute.Parent.Value).FirstOrDefault(),
AreasOfInterest = a.Person.PersonAttributes.Select(att => att.Attribute.Value).ToArray()
}
).SingleOrDefault();
I have done this before in other applications when I was using LINQ to SQL, but using LINQ to Entities when I run the application I get this error
Unable to create a constant value of type 'Namespace.Model.Entities.Address'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Is there anything wrong with the model? As this is complaining about the Address entity.
The solution to the problem I posted at the top How to create and populate a nested ViewModel well was removing the ToList() method calls for the nested collections, but this wont work with the Single() method calls.
Any help will be much appreciated.
Problem is in that you are mixing LINQ to Entities with LINQ to objects in the same LINQ query. Easiest workaround i see is that you first get the results from database using one LINQ query and then project results into required objects in second LINQ query.
//LINQ TO Entities - DbQuery
var dbResults = (from a in db.Applications
where a.ApplicationID == applicationId
select a).ToList();
//LINQ To Objects-- project results from Db into required object
var messageData = (from a in dbResults
select new OrganisationEmailMessageData
{
ApplicationType = a.ApplicationType.EmailMessage,
ApplicationId = a.ApplicationID,
PaymentType = a.PaymentType.Type,
MembershipType = a.MembershipType.Type,
Price = a.MembershipType.Price,
FullName = a.Person.Title + " " + a.Person.Forename + " " + a.Person.Surname,
JobTitle = a.Person.JobTitle,
Department = a.Person.Department ?? string.Empty,
Organisation = a.Person.Organisation != null
? a.Person.Organisation.Name
: string.Empty,
HomeAddress = a.Person.HomeAddressID.HasValue
? ( from add in db.Addresses
where add.AddressID == a.Person.HomeAddressID.Value
select new AddressEmailData
{
Address1 = add.Address1,
Address2 = add.Address2,
Address3 = add.Address3,
Address4 = add.Address4,
Region = add.Region,
Town = add.Town,
PostalCode = add.Postcode,
Country = add.Country.Name
}).Single()
: null,
WorkAddress = a.Person.WorkAddressID.HasValue
? (from add in db.Addresses
where add.AddressID == a.Person.WorkAddressID.Value
select new AddressEmailData
{
Address1 = add.Address1,
Address2 = add.Address2,
Address3 = add.Address3,
Address4 = add.Address4,
Region = add.Region,
Town = add.Town,
PostalCode = add.Postcode,
Country = add.Country.Name
}).Single()
: null,
InvoiceAddress = (from add in db.Addresses
where add.AddressID == a.InvoiceAddressID
select new AddressEmailData
{
Address1 = add.Address1,
Address2 = add.Address2,
Address3 = add.Address3,
Address4 = add.Address4,
Region = add.Region,
Town = add.Town,
PostalCode = add.Postcode,
Country = add.Country.Name
}).Single(),
PublicArea = a.Person.PersonAttributes.Select(att => att.Attribute.Parent.Value).FirstOrDefault(),
AreasOfInterest = a.Person.PersonAttributes.Select(att => att.Attribute.Value).ToArray()
}
).SingleOrDefault();

Resources