I have a User model object and I wan't to when I get this object to get aspnet_User object with it for additional data (usename etc.)
public class User
{
public Guid UserId_fk { get; set; }
public int UserId { get; set; }
public string FirstName { get; set; }
public virtual AspnetUsers AspnetUsers { get; set; }
}
public class AspnetUsers
{
public Guid ApplicationId { get; set; }
public Guid UserId { get; set; }
public string UserName { get; set; }
public string LoweredUserName { get; set; }
public string MobileAlias { get; set; }
public bool IsAnonymous { get; set; }
public DateTime LastActivityDate { get; set; }
}
In database UserId_fk is FK to aspnet_Users.UserId.
How to map this?
Related
There are no primary or candidate keys in the referenced table 'dbo.Client_Master' that match the referencing column list in the foreign key 'FK_dbo.Client_Question_Master_dbo.Client_Master_client_id'.
Could not create constraint or index. See previous errors.
My Client_Master Model
public class Client_Master
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Client_Id { get; set; }
public string Client_Name { get; set; }
public string Client_Address { get; set; }
public string Client_Email { get; set; }
public string Client_Phone { get; set; }
[DefaultValue(" ")]
public string Client_Country { get; set; }
[DefaultValue(" ")]
public string Client_State { get; set; }
[DefaultValue(" ")]
public string Client_Postcode { get; set; }
public bool Is_Active { get; set; }
public long? Created_By { get; set; }
public DateTime? Created_Date { get; set; }
[ForeignKey("Business_Master")]
public long? Business_Id { get; set; }
[ForeignKey("Categories")]
public long? Category_Id { get; set; }
public virtual Categories Categories { get; set; }
public virtual Business_Master Business_Master { get; set; }
[JsonIgnore]
public virtual ICollection<Client_Question_Master> Client_Question_Master { get; set; }
}
And My Client_Question_Master Modal
public class Client_Question_Master
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long client_question_master_id { get; set; }
[ForeignKey("Client_Master")]
public long? client_id { get; set; }
public virtual Client_Master Client_Master { get; set; }
[ForeignKey("Question_Types")]
public long? question_type_id { get; set; }
public virtual Question_Types Question_Types { get; set; }
public string question { get; set; }
public long order_no { get; set; }
public bool isContribute { get; set; } = true;
[ForeignKey("Section_Master")]
public long? section_id { get; set; }
public virtual Section_Master Section_Master { get; set; }
public double amount { get; set; }
public bool isActive { get; set; } = true;
public bool isRequired { get; set; } = true;
public bool isComment { get; set; } = true;
public string values { get; set; }
public bool isRevenue { get; set; }
public bool isStaff { get; set; }
public bool isMarketing { get; set; }
public DateTime created_date { get; set; } = DateTime.Now;
}
After add-migration during updating database it is giving me error.
Your usage of the ForeignKey attribute is the wrong way round, when using a nullable foreign key.
For example you use:
[ForeignKey("Client_Master")]
public long? client_id { get; set; }
public virtual Client_Master Client_Master { get; set; }
However it should be:
public long? client_id { get; set; }
[ForeignKey("client_id")]
public virtual Client_Master Client_Master { get; set; }
You tell EntityFramework what property is the foreign key. This prevent it from creating a field that has the same datatype as the primary key.
Check your edmx file.Edmx may not have that column as Primary key in another table which you are using as foreign key.
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?
I am trying to add an entry to a table that holds a users browsing history information. However, when trying to save the addition an SqlException is thrown:
Cannot insert duplicate key row in object 'dbo.AspNetUsers' with
unique index 'UserNameIndex'. The duplicate key value is
(exampleUserName). The statement has been terminated.
A user is has many browsing histories but a browsing history can only be attached to one user so there is a user as part of the BrowsingHistory DataModel:
namespace DataModels
{
[Table("BrowsingHistory")]
public class BrowsingHistory
{
[Key]
public int BrowsingHistoryId { get; set; }
public int ProductId { get; set; }
public System.DateTime DateTime { get; set; }
public int DeviceId { get; set; }
public int UserId { get; set; }
public virtual AspNetUsers User { get; set; }
public virtual Device Device { get; set; }
public virtual Product Product { get; set; }
}
}
It is to note that I am using the Microsoft Identity classes for my authentication. The user class looks as follows:
namespace DataModels
{
using System;
using System.Collections.Generic;
[Table("AspNetUsers")]
public class AspNetUsers
{
public AspNetUsers()
{
BrowsingHistories = new HashSet<BrowsingHistory>();
Orders = new HashSet<Order>();
AspNetUserClaims = new HashSet<AspNetUserClaims>();
AspNetRoles = new HashSet<AspNetRoles>();
}
[Key]
public int Id { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string HouseName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string ContactNumber { get; set; }
public virtual ICollection<BrowsingHistory> BrowsingHistories { get; set; }
public virtual ICollection<Order> Orders { get; set; }
public virtual ShoppingCart ShoppingCart { get; set; }
public virtual ICollection<AspNetUserClaims> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetRoles> AspNetRoles { get; set; }
}
}
The error occurs when trying to save the addition in the repository. On the _context.SaveChanges() line the method below.
public void CreateBrowsingHistoryEntry(BrowsingHistory bhe)
{
_context.BrowsingHistory.Add(bhe);
_context.SaveChanges();
}
Any help with this issue would be greatly appreciated.
I have a the following classes
namespace MyClass.Models
{
public class Address : IIdentity
{
public string id { get; set; }
public DateTime updatedAt { get; set; }
public string user_id { get; set; }
public int building_number { get; set; }
public string street { get; set; }
public string area { get; set; }
public string county { get; set; }
public string country { get; set; }
public string postcode { get; set; }
public bool iscustomer { get; set; }
public bool islive { get; set; }
public string customer_id { get; set; }
public string store_id { get; set; }
public string phone_id { get; set; }
}
}
and
namespace MyClass.Models
{
public class User : IIdentity
{
public string id { get; set; }
public DateTime updatedAt { get; set; }
public string username { get; set; }
public string password { get; set; }
public bool isrestricted { get; set; }
public bool isbanned { get; set; }
public DateTime renewaldate { get; set; }
public string address_id { get; set; }
public string userlevel { get; set; }
}
}
What I am trying to do is create some test data to propagate through to my database so I can test my MVC5 website.
I am attempting to perform a look up on my instance of User within the Address class like so
user_id = context.User.FirstOrDefault(t=>t.address_id == id)
where id points to the id within the class I and trying instantiate.
VS2013 is saying that id does not exist in the current context which makes sense. Is there a way to do what I'm trying to achieve or am I better off setting the my _id from within the class itself and will that be okay when I run update-database from within the package manager console?
For example, the address class would become
namespace MyClass.Models
{
public class Address : IIdentity
{
public string id { get; set; }
public DateTime updatedAt { get; set; }
public string user_id { get {user_id = Users.FirstOrDefault(t=>t.address_id == id).id; } }
public int building_number { get; set; }
public string street { get; set; }
public string area { get; set; }
public string county { get; set; }
public string country { get; set; }
public string postcode { get; set; }
public bool iscustomer { get; set; }
public bool islive { get; set; }
public string customer_id { get {customer_id = Customers...;} }
public string store_id { get {store_id = Stores...;} }
public string phone_id { get {phone_id = Phones...;} }
}
}
I created:
custom custom membership provider
custom role provider
an user model
an role model
It create me the 2 custom tables correctly.
Now I want to create the table between Users and Roles with 2 columns: RoleId, UserId
I should I tweak my models to teach to EF to create this relationship table (UsersInRole)?
User model:
public class User
{
[Key]
public int UserId { get; set; }
[Required]
public Int32 CompanyId { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String Email { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLockedOut { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime LastLockoutDate { get; set; }
}
Role model:
public class Role
{
[Key]
public int RoleId { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
public ICollection<string> AssignedUsers { get; set; }
}
If you are using code-first EF, then all you should need to do is add a collection of the Users to the Role class and vice-versa. EF takes this two-way link as a signal to create a many-to-many relationship in the underlying data store. To summarize, your classes would be augmented something like this...
public class User
{
...
List<Role> Roles {get; set;}
}
public class Role
{
...
List<User> Users {get; set;}
}
public class Role
{
[Key]
public int RoleId { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
public ICollection<User> AssignedUsers { get; set; }
}
public class User
{
[Key]
public int UserId { get; set; }
[Required]
public Int32 CompanyId { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String Email { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLockedOut { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime LastLockoutDate { get; set; }
public ICollection<Role> Roles{ get; set; }
}