I have created an mvc4 webapi project in VS2012RC and used EF4.3 in my project for Code first.
I used default membership provider. How can i use the UserName as foreign key in another model.
I tried this code ,
[ForeignKey("RegisterModel")]
public string UserName { get; set; }
public virtual RegisterModel User { get; set; }
Is there anything wrong with my code?
Please help
Thanks,
You cannot use UserName because UserName is not primary key in Users table. Only primary keys from principal table can be used as foreign keys in dependent table when using EF because EF doesn't understand unique constraints used in database.
Related
I'm working on an ASP.NET MVC project, I use Entity Framework (Database First), I created a data model depend on SQL server database, I created a Table in the database and I updated the data model from the database, and when I try to add a record to the new table I created (this table doesn't have a PK) I got an error, when I search about the error I Understood that in Entity Framework need to have a PK for Entity.
So I ASK if I can set a Primary Key for an Entity without affect database, or any other solution to solve this problem.
You can use partial Class for set Key and without effect Original Model and Database
// orginal class **Entity** `YourEntity.cs`
public class YourEntity
{
public int Id { get; set; }
}
Then create a new Class must name different ordinal class ex YourEntityMeta.cs it is physical name
// must change name ordinal class `YourEntity.cs` but add **partial** keyword
[MetadataType(typeof(Metadata))]
public partial class YourEntity
{
sealed class Metadata
{
[Key]
public int Id { get; set; }
}
}
Entity Framework always needs a primary key column with name id. Add a column (id) in the database table and set "Is Identity: true" for it. Then update the database model of your project.
I'm using Entity Framework to map some tables, but I can't do this unless I declare some column as the primary key.
The problem here is that my table in my database don't have a primary key and has millions of rows. I don't have permission to create a new Id column.
[Table("MYTABLE")]
public class myTable
{
[Column("NUMX")]
public virtual string NumX { get; set; }
[Column("NAME")]
public virtual string Name { get; set; }
[Column("AGE")]
public virtual int AGE { get; set; }
}
Obs: If I add the [Key] attribute to some column like Age, it works, but returns the wrong data.
Is there some way to omit the primary key?
I Figured out the problem.
Composite Keys works for me:
eg:
In my Context I defined some keys, not only one, but three keys:
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
**//Here is the secret**
modelBuilder.Entity<MyModel>().HasKey(x => new { x.NumX, x.Name,x.Age});
}
}
Entity Framework requires a primary key unlike SQL.
EF use the primary key to uniquely identify rows (for example when you use .Find() or to perform update operations).
Infact not having a primary key remember a SQL VIEW, where you can only read data.
If any of the columns uniquely identify a certain row set it as a primary key (it can't be NULL) also if in Sql it isn't a key.
Otherwise if the combination of the columns are uniquely, create a composite key with these columns.
Remember that you should have a primary key in the 99% of cases, when you don't have a primary key you should stop and think if it make sense.
I am using MVC Core with the default individual user authentication.
I added FullName field to AspNetUsers Table and it is working fine.
I need to create a relationship between my tables to the id field in the AspNetUsers table so I can get the fullname of the user.
I have no idea on how to create relationship in Entity framework, I tried to add the following in the ApplicationUser Class
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public mytable T { get; set; }
}
and
in mytable model, I added the following
public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
unfortunately, I am getting the following error:
The entity type 'IdentityUserLogin' requires a primary key to be defined
any idea?
The first issue solved by following link
https://forums.asp.net/post/6144294.aspx
the IdentityUserLogin' requires a primary key to be defined also solved by
https://stackoverflow.com/a/40824620/7046796
I am working on a MVC web site with Claims Authentication and also using Thinktecture IdentityModel.
Each user has a set of CLAIMS: City, Username, Email, Roles, Birthdate.
I have 3 tables in the database: USERS, USERS_PROFILES and USERS_CLAIMS.
USERS contains the columns Username and Email;
USERS_PROFILES contains the columns City and Birthdate.
I am saving these values in these tables ... And I save the Roles in the USERS_CLAIMS table.
When I load a user I fill the ClaimsIdentity with the data from these tables.
THE QUESTION IS:
When I create a user should I, for example, save the email both in USERS table and in USERS_CLAIMS table?
It seems data replication but I am not sure ... Or should I save in only one of them?
What is your approach to this? And what kind of claims, beside roles, do you have that don't fit in a USERS or USERS_PROFILE table?
Thank You,
Miguel
As you're using MVC (Model View Controller), why don't you use Models ?
Your ClaimsIdentity is a model, just create a ClaimsIdentityModel.cs in your Model folder, and use it like this :
public class ClaimsIdentityModel
{
public string Username { get; set; }
public string Email { get; set; }
public string City { get; set; }
public Datetime Birthdate{ get; set; }
}
Then, when you load your user, just fill a ClaimsIdentityModel. And you're done.
As name of each table suggest, the values shall represent those only.
Users are identified as by usernames. Email is one of the claim done by the User.
Roles are also claims, so as City.
If you are creating profile table and adding city in profile, it shall be avoided to add it in Claims table. But you need to handle requirement of City as claim by queries Profile table and providing value as claim as needed.
ClaimsIdentity is System.Security.Principal.GenericIdentity type that is used to identify the user in claim based approach.
(Making Model will be helpful in the View)
In my asp.net mvc4 sample i have table in the name of Sample with three column as Name,Dept and Id.In this Id as identity and primary.I get a value for Name and Dept from user and insert that value to Sample table of entity framework.It pass value '0' to Id.And i got an error as "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries".Please help me.
set "autoincrement" on the column and set the id as primary key in sql server ..
In EF code-first this is done by data annotations. Make sure you recreate your table (or database) after changing the scheme.
public class Sample
{
[Key]
[Required]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //auto increment id
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Dept { get; set; }
}
You don't need to pass an integer for Id. EF will resolve this automatically. Just create the object by filling in the name and the dept. By saving the changes to the database, EF will automatically fill in the auto generated Id.