Entity Framework Code First - using UserId key of Memberships/Users table as Foreignkey in a custom table - asp.net-mvc-4

I am trying to create a SQL table to include additional user information.
I want it to be created by Migrations in VS2012 (package console => update-database).
I see that there are two tables using UserId column as key: Memberships and Users tables.
I am trying to define the following class and map it to SQL table via Migrator:
[Key]
[Column(Order = 0)]
[ForeignKey("User")]
public Guid **UserId** { get; set; }
[Key]
[Column(Order = 1)]
[ForeignKey("Category")]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
**public virtual User User { get; set; }**
Although it is obvious in the Users SQL table that UserId column is the key, I get this error message:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'User' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Users' is based on type 'User' that has no keys defined.
What I am missing here? Might be that Microsoft.VisualBasic.ApplicationServices.User / System.Web.Security.MembershipUser classes weren't necessarily mapped to the tables this way and vise versa, and therefore the UserId property is not declared is Key dataannotation?
I am open for other solutions for this problem.
Big Thanks!

I am currently using asp.net mvc4 with Azure db.
When I want to use UserId in other tables from UserProfile. Notice in AccountModels there is class UserProfile:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
Now, let's say your category is created by certain user, you can link category entry to user in following way.
[Table("Category")]
public class Category
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CategoryId { get; set; }
public UserProfile CreatorUserId { get; set; }
}
Otherwise, you can always use UserProfile as model.

Related

Why EF core tries to add navigational property into DB and not only the Id of foreign model?

I was wondering why EF tries to add also foreign models.
Example:
public class Category
{
public int Id { get; set; }
public string Name{ get; set; }
}
public class Content
{
public int Id { get; set; }
public string Name{ get; set; }
public Category Category{ get; set; }
}
After creating "Content" using migrations, I have a table that includes the id of category. That's create. So I have three columns: Id, name and the categoryId. Seems EF "knows" that this should be just the primary key of Category, that needs to get stored.
Than I tried to add something with EF.
var cat = new Category {Id = 2, Name = "awesomeCat"})
var addContent = new Content({Name = "test", Category = cat})
Now I want to add a Content by using _context.Add(addContent). I was expecting a single insert into db that uses the name "test" and the categoryId 2. Id will be generated by DB.
But instead EF also tries to add a new Category into the category table.
So I took a deeper look and seems EF "does" not know it already exists and was not maintaining any transactions about the category model.
I gave it another try and used no new category, instead I was loading it before:
var cat = _context.findById("2");
and assigned this one instead. Now EF should know that this one already exists and does not have to add it in category table.
Could it be, that my model is just wrong.
Do I need to use it more like:
public class Content
{
public int Id { get; set; }
public string Name{ get; set; }
public int? CategoryId{ get; set; }
[ForeignKey("CategoryId")]
public Category Category{ get; set; }
}
Won't I get two category references then?
You need to tell EF Core it's a primary key and to generate the key
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
public class Content
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
Then you don't need to mark [ForeignKey("CategoryId")], EF Core will turn the object reference into an ID in the database
If I misunderstood your question, ask again :)
EF Core has internal tracking of entities. When you simply new up a category, it's not being tracked. When you add the content, EF will track any related entities as well, which would include your category, which will by default be tracked as "Added". You have a few choices.
Don't "new up" an existing category, but rather, retrieve it from the database. If EF pulls it from the database, then it will be tracked, and will not be added again.
You can explicitly track the category instance you newed up and set it's state to "Unchanged".
_context.Attach(category);
_context.Entry(category).State = EntityState.Unchanged;
_context.Add(content);
The best method is to not deal with the reference property at all, and use an explicit foreign key property. Add a property to your content class:
public int CategoryId { get; set; }
Then, you can simply set this id, instead of the Category prop:
var addContent = new Content { Name = "test", CategoryId = 2 };
EF will backfill the reference property after save.

How to add foreign key in a model using ASP.NET ( MVC6 framework)

I am new to ASP.NET and trying out the new MVC 6 framework. i want to create an To do list App. After user authentication, I am redirecting to a dashboard page where I want to display to do tasks. I have created a model Task, but i am unsure about how to add a Foreign Key for the user id so that when i redirect the user to the dashboard page I can query based on the user's id.
public class Task
{
public int Id { get; set; }
// i want to add a fk to aspnetuser id here
}
Thank you for your help.
public class Task
{
public int Id { get; set; }
public int AnyNameForId { get; set; }
[ForeignKey("AnyNameForId")]
public AspnetUser User { get; set; }
}
public class AspnetUser
{
public int Id { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}
suppose u have class XYZ having Id as primary key.
now u want to class XYZ's Id as foreign key in class ABC,
So, it can be done like writing the following in class ABC
public Guid XYZId{get;set;}
public XYZ xyz{get;set;}`
xyz is an object of class XYZ.
.net core will automatically take XYZId as fk in class ABC.....PLZ note that Id Should be the primary in class XYZ

One to one relationship - code first

I'm trying to make one to one relationship. I don't want to use fluent API if it is not necessary. This is what I tried so far:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class Person
{
public int Id { get; set; }
[ForeignKey("UserId")]
public UserProfile UserProfile { get; set; }
}
Yes, I know there are few similar questions outhere, but none of them were short and clear. Lot of them also did not work.
It depends a little on what type of table structure you want to achieve. There are various ways of doing this, and there is a good walkthrough for all the options, from Shared Primary Key Assocations to One-to-One Foreign Key Associations in those links. Unfortunately those links make more use of Fluent than Annotations. The samples below use Annotations, as you need.
Shared Primary Key
In theory the Shared Primary Key (horizontal table partitioning, in database terms) is the "correct way". It is also the smallest change you need to do to be able to generate a migration (which will use a Shared Primary Key Association). Note that I would change Person.Id to Person.UserId to better show your intent:
// tested in EF 5 and MVC 4.5.
[Table("UserProfile")]
public class UserProfile {
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
[Table("Person")] // not required, added for clarity in sample code
public class Person {
// Note the change of property name to reflect that this is a shared primary key,
// using the UserId column in UserProfile as the Primary Key
[Key]
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }
}
// The generated migration:
public partial class AddTable_Person : DbMigration
{
public override void Up() {
CreateTable(
"dbo.Person",
c => new {
UserId = c.Int(nullable: false),
})
.PrimaryKey(t => t.UserId)
.ForeignKey("dbo.UserProfile", t => t.UserId)
.Index(t => t.UserId);
}
public override void Down(){
DropIndex("dbo.Person", new[] { "UserId" });
DropForeignKey("dbo.Person", "UserId", "dbo.UserProfile");
DropTable("dbo.Person");
}
}
this then gives you, in effect a 1:0-1 relationship between UserProfile (which is mandatory) and People (which is optional, but can have one per person at the most.
If you want to use Id in Person then do the following (the migration will change accordingly):
public class Person {
public int Id { get; set; }
[ForeignKey("Id")]
public UserProfile UserProfile { get; set; }
}
Shared Primary Key with two-way navigation
If you want to navigate from UserProfile to Person you have more work to do. Simply adding public virtual Person Person { get; set; } to UserProfile will give you an error:
Unable to determine the principal end of an association between the types 'Test.Models.UserProfile' and 'Test.Models.Person'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
So, we fix it with [Required] on the Person.UserProfile property (Person requires UserProfile). This gives the same migration as before.
// tested in EF 5 and MVC 4.5.
[Table("UserProfile")]
public class UserProfile {
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
[ForeignKey("UserId")]
public virtual Person Person { get; set; }
}
[Table("Person")] // not required, added for clarity in sample code
public class Person {
[Key]
public int UserId { get; set; }
[ForeignKey("UserId")]
[Required]
public virtual UserProfile UserProfile { get; set; }
}
Again, this works if you use Id for Person instead of UserId:
public class Person {
[Key]
public int Id { get; set; }
[ForeignKey("Id")]
[Required]
public virtual UserProfile UserProfile { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual Person Person {get;set;}
}
public class Person
{
public int Id { get; set; }
public int UserProfileUserId { get; set; } //Foreign Key
public virtual UserProfile UserProfile { get; set; }
}
If you want to create a one-to-one relationship the first thing you must clarify is what is the principal and what the dependent entity in this relationship. Can a Person exist without UserProfile or can a UserProfile exist without Person?
Because you have started to apply a [ForeignKey] attribute in Person I am assuming now that Person is the dependent, i.e. it cannot exist without UserProfile.
Correct application of the [ForeignKey] attribute would then be:
public class Person
{
[ForeignKey("UserProfile")]
public int Id { get; set; }
public UserProfile UserProfile { get; set; }
}
I am not sure if that is sufficient because you don't have a Person navigation property in UserProfile. If it doesn't work add this property to UserProfile:
public Person Person { get; set; }
If you don't want to have such a navigation property you can't avoid Fluent API:
modelBuilder.Entity<Person>()
.HasRequired(p => p.UserProfile)
.WithOptional();

Entity Framework and using Fluent API for mapping two entities to another one

Scenario seems to be trivial and I'm really confused on what I'm doing wrong.
So, I have a Client class
public class Client
{
[Key]
public int ClientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Account Account { get; set; }
}
Employee class
public class Employee
{
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Account Account { get; set; }
}
and an Account class
public class Account
{
[Key]
public int AccountID { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public virtual Employee Employee { get; set; }
public virtual Client Client { get; set; }
}
Both Client and Employee may have an Account or not ( online access is optional ). As database is not compatible with EF namingconvention I have to come up with Fluent API explicit mappings.
Both Client and Employee tables have "AccountID" column that I'm trying to use to build a relation.
modelBuilder.Entity<Client>()
.HasOptional(e => e.Account)
.WithRequired(a => a.Client)
.Map(m => m.MapKey("AccountID"));
modelBuilder.Entity<Employee>()
.HasOptional(e => e.Account)
.WithRequired(a => a.Employee)
.Map(m => m.MapKey("AccountID"));
but I get
Schema specified is not valid. Errors:
(15,6) : error 0019: Each property name in a type must be unique. Property name 'AccountID' was already defined.
(16,6) : error 0019: Each property name in a type must be unique. Property name 'AccountID' was already defined.
so, is there a way to fix this other than modification of the table/entity structure?
Turns out you don't need Fluent API in this case, what you need is to DataAnnotate your properties in Entities with InverseProperty attribute
[InverseProperty("AccountID")]
There is a great answer by Ladislav Mrnka in Entity Framework 4.1 InverseProperty Attribute question
However if anyone knows how to do that correctly with Fluent answers are highly appreciated

NHibernate: controlling Bidirectional ManyToMany. Adding from one entity and removing from the other entity

I have 2 tables with manyToMany relationship. user can have many groups and groups can have many users.
public class User
{
public virtual Guid Id { get; set; }
public virtual UInt64 UserId { get; set; }
public virtual IList<Group> Groups{ get; set; }
}
public class Group
{
public virtual Guid Id { get; set; }
public virtual Guid GroupGuid { get; set; }
}
I use Fluent NHibernate to AutoMap them as follows:
.Override<User>(obj => obj.HasManyToMany(x => x.Groups).Table("UserToGroup").Cascade.AllDeleteOrphan())
As a result Nhibernate produce 3 tables:
1. Users - Mapped object table
2. Groups Mapped Object table
3. UserToGroup - generated association table
The requirement is to have the following functionality on these tables:
1. AddUser(UInt64 UserId, IEnumerable groups)
2. RemoveGroup(GroupGuid groupGuild)
3. Dictionary> GetGroupToUsers();
AddUser method is work Ok, All table updated OK:
* Insert of new user in User table. OK
* Insert of new group in Group table. OK
* Insert of new relations recods in UserToGroup table. OK
I use the following code to add a User (including groups):
public void AddUser(User userData, IList<Guid> groupIds)
{
User user = new User();
user.UserId = userData.UserId;
IList<User> Users = new List<Users();
Users.Add(user);
IList<Group> groups = new List<Group>();
foreach (Guid groupId in groupIds)
{
Group grp = new Group();
grp.GroupGuid = groupId;
grp.Users = Users;
groups.Add(grp);
}
user.Groups = groups;
Session.Save(user);
}
I use the following code to Remove group:
public void RemoveGroup(GroupGuid groupGuild)
{
IList<Group> groupsToRemove = Session.QueryOver<Group>().Where(
row => row.GroupGuid == groupGuild).List();
foreach (Group group in groupsToRemove)
{
group.Users.Clear();
Session.Delete(group);
}
}
RemoveGroup method failed with the following exception:
threw exception:
NHibernate.Exceptions.GenericADOException: could not delete: [StorageObject.Group#11111111-1111-1111-1111-111111111111][SQL: DELETE FROM "Group" WHERE Id = ?] ---> System.Data.SqlServerCe.SqlCeException: The primary key value cannot be deleted because references to this key still exist. [ Foreign key constraint name = FK4B29424018FA0CD4 ]
I understand that Group table can't be delete since the reference UserToGroup table point to Group table.
1st question: how can I make hibernate to understand that I want to be able to controller this manyToMany relation from both side:
Add users with groups - from user side.
And delete groups - from group side
I tried to move Inverse to the User table but in this case when I add a User the association table is not populate.
What is the best way to define this kind of manyToMany relation?
Update:
Another way I tried is to have List of Users also in Groups in this configuration removeGroup is wokring but addUser in not working for specific scenario:
public class Group
{
public virtual Guid Id { get; set; }
public virtual Guid GroupGuid { get; set; }
public virtual IList<User> Users{ get; set; }
}
public class User
{
public virtual Guid Id { get; set; }
public virtual UInt64 UserId { get; set; }
public virtual IList<Group> Groups{ get; set; }
}
Now I have a bidirectional many to many.
My Fluent mapping is:
.Override<User>(obj => obj.HasManyToMany(x => x.Groups).ParentKeyColumn("UserId").ChildKeyColumn("GroupId").Table("UserToGroup").Cascade.SaveUpdate()
.Override<Group>(obj => obj.HasManyToMany(x => x.Users).ParentKeyColumn("GroupId").ChildKeyColumn("UserId").Table("UserToGroup")
If I use this configuration RemoveGroup works fine but AddUser is not working for the following case:
When adding 2 Users which contains the same Group the association table delete the first relation and holds just the last reference instead of having both relations.
Please advise.
Try to add an inverse collection in Group:
public class Group
{
public virtual Guid Id { get; set; }
public virtual Guid GroupGuid { get; set; }
public virtual IList<User> Users { get; set; }
}
In your mapping:
.Override<Group>(obj => obj.HasManyToMany(x => x.Users).Table("UserToGroup").Inverse().Cascade.SaveUpdate())
Your Remove method:
public void RemoveGroup(GroupGuid groupGuild)
{
IList<Group> groupsToRemove = Session.QueryOver<Group>().Where(
row => row.GroupGuid == groupGuild).List();
foreach (Group group in groupsToRemove)
{
group.Users.Clear(); // Removes references from all users pointing to that group
Session.Delete(group);
}
}
When you commit the transaction, the references should be automatically removed. I never tried this by myself, but it might work for you.