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 = ""
});
}
Related
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!
I am using code-first Entity Framework in my ASP.NET MVC project
I have these tables
User
public class User:IBaseEntity
{
public User()
{
UserRoles = new List<UserRole>();
}
public int ID { get; set; }
public int RoleId { get; set; }
public string Email { set; get; }
public string Password { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public string Company { set; get; }
public string Address1 { set; get; }
public string Address2 { set; get; }
public string City { set; get; }
public string PostalCode { set; get; }
public string Country { set; get; }
public string State { set; get; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
Role
public class Role : IBaseEntity
{
public int ID { get; set; }
public string RoleName { get; set; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
}
UserRole
public class UserRole : IBaseEntity
{
public int ID { get; set; }
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
IBaseEntity
public interface IBaseEntity
{
int ID { get; set; }
}
I need seed data User with UserRole
How can I put UserRole in method create User?
public void CreateRoles(CMSDbContext context)
{
if (context.Roles.Count() == 0)
{
List< Role> listRole = new List<Role>()
{
new Role()
{
RoleName = "Admin",
Active = true,
CreatedOn = DateTime.Now
},
new Role()
{
RoleName = "User",
Active = true,
CreatedOn = DateTime.Now
}
};
context.Roles.AddRange(listRole);
context.SaveChanges();
}
}
public void CreateUser(CMSDbContext context)
{
if (context.Users.Count() == 0)
{
List<User> listUser = new List<User>()
{
new User()
{
FirstName = "David",
LastName = "Lima",
Active = true,
Email = "admin#domain.com",
Address1 = "New York",
Address2 = "Chicago",
Company = "Test",
CreatedOn = DateTime.Now,
PostalCode = "123456",
State = "Test",
City = "test",
UserRoles =???
Password = CMS.Common.HashMD5.CreateMD5("12356")
}
};
context.Users.AddRange(listUser);
context.SaveChanges();
}
}
}
Please focus on method CreateUser have property UserRole, not sure what I can put here. I also create some roles in Role table (admin, user)
I am getting stuck at this point.
Any help will be appreciated
Thanks all
I have a Contractor class and a Musicians Class which inherits the Contractor class. I am running migration and it will only build one Contractor table with Musicians fields included. I want a Contractor table and Musicians table that follows my domain models. It creates Instrument table correctly. Does this have something to do with the fact I am using inheritance on the classes?
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
}
public class Musician : Contractor
{
public Guid MusiciansId { get; set; }
public string WebsiteLink { get; set; }
public string YouTubeLink { get; set; }
public string SoundCloudLink { get; set; }
public string ReverbNationLink { get; set; }
public int YearsOfExperience { get; set; }
[DataType(DataType.Date)]
public DateTime NextDateAvailable { get; set; }
public Instrument Instrument { get; set; }
public int InstrumentId { get; set; }
public Contractor Contractor { get; set; }
public Guid ContractorId { get; set; }
}
My Migration script :
CreateTable(
"dbo.Contractor",
c => new
{
ID = c.Guid(nullable: false),
FirstName = c.String(),
LastName = c.String(),
Email = c.String(),
ZipCode = c.String(),
Phone = c.String(),
Description = c.String(),
CreateDate = c.DateTime(nullable: false),
SuspendDate = c.DateTime(nullable: false),
ImageData = c.Binary(),
ImageMimeType = c.String(),
ImageName = c.String(),
Suspended = c.Boolean(nullable: false),
UnionMember = c.Boolean(),
MusiciansId = c.Guid(),
WebsiteLink = c.String(),
YouTubeLink = c.String(),
SoundCloudLink = c.String(),
ReverbNationLink = c.String(),
YearsOfExperience = c.Int(),
NextDateAvailable = c.DateTime(),
InstrumentId = c.Int(),
ContractorId = c.Guid(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Contractor", t => t.ContractorId)
.ForeignKey("dbo.Instrument", t => t.InstrumentId, cascadeDelete: true)
.Index(t => t.InstrumentId)
.Index(t => t.ContractorId);
It is not a good idea to use inheritance in model classes.
You can add Type value for your Contractor and create another table for each type of contractor (Musician for example):
public enum ContractorType
{
Musician = 0
}
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
public ContractorType contractorType { get; set; }
public Musician Musician { get; set; }
}
After doing some research the answer is: [Table] attribute above Musicians class.
http://www.codeproject.com/Articles/796521/Inheritance-in-Entity-Framework-Table-Per-Type
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();
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>