EF Code First composite key mapping - ef-code-first

I have 2 tables. User and Roles.One user can have meany roles. so i created another table called RoleUser. how should i implement this in code first(i want to insert and update operation)
thanks in advance

Natively you should be able to declare the two tables (with properties pointing to the other) and EF will pick up on the many-to-many relationship (and create the intermediary table with two FK's)
public class user
{
public int id { get; set; }
public string username { get; set; }
// user can be within multiple roles
public ICollection<role> roles { get; set; }
}
public class role
{
public int id { get; set; }
public string name { get; set; }
// role can have many users
public ICollection<user> users { get; set; }
}

Related

EF Core one-to-many relationship with multiple contexts (databases)

I have contexts with entities like this:
public class CompanyContext : DbContext
{
public DbSet<StoreModel> Stores { get; set; }
// Other entities
}
public class DepartmentContext : DbContext
{
public DbSet<OrderModel> Orders { get; set; }
// Other entities
}
public class StoreModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<OrderModel> ReceivedOrders { get; set; }
public virtual ICollection<OrderModel> PreparedOrders { get; set; }
public virtual ICollection<OrderModel> IssuedOrders { get; set; }
}
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public StoreModel GettingStore { get; set; }
public StoreModel PreparingStore { get; set; }
public StoreModel IssuanceStore { get; set; }
}
For example a user makes an order in storeA, but wants to receive it in storeC, and it order will preparing in storeB. And I needs a statiscics about store received/prepared/issued orders.
When I try to create a migrations, EF throws exceptions "Unable to determine the relationship represented by navigation 'OrderModel.GettingStore' of type 'StoreModel'" and "Unable to determine the relationship represented by navigation 'StoreModel.IssuedOrders' of type 'ICollection<OrderModel>'". If I understand correctly, this happens because entities are defined in different contexts.
Now I just use next model:
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public Guid GettingStoreId { get; set; }
public Guid PreparingStoreId { get; set; }
public Guid IssuanceStoreId { get; set; }
}
This works fine, but perhaps there are options that allow to create such a structure using navigation properties, with correct relationships between these entities from different contexts(databases).
First, the map of a different database was not placed in tables of different application formats, so think that you have a domain that should be well defined in your application, that way you would have the mapping of your application like this:
public class DomainNameContext: DbContext
{
public DomainNameContext(): base()
{
}
public DbSet<StoreModel> Stores { get; set; }
public DbSet<OrderModel> Orders { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// config mapping methods
}
}
another thing, the relation you are using doesn't work so you can't have a repetition of Orders within the same class because this is not one -> many, this statement means that a StoreModel line can have many lines in the OrderModel this way would be like this
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public Guid StoreModeId { get; set; } // this part will show the entity framework that this is the fk it will correlate
public StoreModel StoreModel { get; set; }
}
public class StoreModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<OrderModel> OrderModels { get; set; }
}
see that if you are wanting to have many StoreModel related to many OrderModel then you need to use many -> many which microsoft documentation foresees to use as well
good to map this within its context it is necessary in OnModelCreating to use its mapping like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// config mapping methods
modelBuilder.Entity<StoreModel>()
.HasMany<OrderModel>(g => g.OrderModels )
.HasForeignkey<Guid>(s => s.StoreModeId )
}
you can have a look at the microsoft documentation enter link description here, enter link description here
now if you need to map between contexts you will have to use dapper to make separate queries in separate bases the entity has support for that in this link enter link description here
and then you can make the necessary inner joins so that you can use it but natively this does not exist, I advise you to rethink your database so that it can make more sense to a relational model, perhaps putting types for your StoreModel and OrderModel so you can use the way I wanted the types GettingStore, PreparingStore, IssuanceStore using an enum for this to make it explicit

EF-Code First navigation property foreign key in complex type

I have complex type for Audit fields
My complex type:
[ComplexType]
public class AuditData {
[Column("CreatorUserId")]
public int? CreatorUserId { get; set; }
public DateTime? CreationTime { get; set; }
[Column("ModifierUserId")]
public int? ModifierUserId { get; set; }
public DateTime? ModificationTime { get; set; }
}
My base Entity (all other inherti this one) has AuditData property:
public abstract class Entity : IEntity, IAuditedEntity, INotifiedDbContextBeforeSave
{
// Summary:
// Unique identifier for this entity.
public int Id { get; set; }
public bool IsActive { get; set; }
public int Old_Id { get; set; }
public string Old_TableName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public AuditData AuditData { get; set; }
// can this 2 lines below work as navigation property with foreign key in complex type
public virtual User CreatorUser { get; set; }
public virtual User ModifierUser { get; set; }
//... other fields
}
I have 2 navigation properties CreatorUser and ModifierUser.
I know you cant have navigation property in ComplexType but can my navigation property on entity be mapped with foreign key in complexType
something like:
[ForeignKey("CreatorUserId")] // --> should point to AuditData.CreatorUserId
public virtual User CreatorUser { get; set; }
becouse CreatorUserId will be property in every entity but EF is not aware of it.
Mybe there is solution in fluent API ?
The official documentation says:
Complex types are non-scalar properties of entity types that enable scalar properties to be organized within entities. Like entities, complex types consist of scalar properties or other complex type properties. Because complex types do not have keys, complex type objects cannot be managed by the Entity Framework apart from the parent object.
It follows that that complex types can not participate in any relations among entities, so they can't contain foreign keys

How can I create two types of users in MVC5?

I'm creating MVC5 app, and I'm already using ASP.NET Identity to create users. So, I already have the AspNetUsers table, and whenever user registers I get an entry there. I also have an Admin role, where I manually specify, which registered user is an admin. On the other hand, I also need to register Businesses, and much like normal Users, they will be able to log-in, register, and do some stuff. The point is that they will have both some similar and different fields with/from the normal users. For example, they will also have, e-mail address, password (which I want to be hashed like for normal users), e-mail confirmation, unique id etc. But they have different fields for more information, like their address, zip, country, category, etc. which normal users don't have. How can I achieve this in MVC?
Should I do something like the ApplicationUser class?
public class ApplicationUser : IdentityUser
I mean, should I inherit my Business model from the IdendityUser? If yes, how will my model know which of the fields from IdentityUser to use and which not?
Here is my current Business model:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
[ForeignKey("Category")]
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
[ForeignKey("Subcategory")]
public int SubcategoryID { get; set; }
public virtual Subcategory Subcategory { get; set; }
public string BusinessAddress { get; set; }
public string BusinessZip { get; set; }
public string BusinessPhone { get; set; }
public string BusinessDescription { get; set; }
public string Facebook { get; set; }
public string Twitter { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
[Range(0.0, 5.0)]
public double BusinessRating { get; set; }
public virtual ICollection<Review> Reviews { get; set; }
}
So, apart from those fields, I want my table to include the stuff similar to AspNetUsers, like Email, EmailConfirmed, PasswordHash, SecurityStamp, etc.
EDIT:
Please note that some of my fields in the Business model are required. And also below you can find my ApplicationUser class.
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
Use simple inheritance:
public class Business : ApplicationUser
{
...
}
You'll end up with a Discriminator column in your AspNetUsers table that will help Entity Framework identity which class it should instantiate for the row (Business or ApplicationUser). Then you can either just query as normal or if you only want one particular type or another, you can use OfType<T>:
var businessUsers = db.Users.OfType<Business>();
Note: By default, Entity Framework handles simple inheritance with a single table with a Discriminator column. For most cases this works just fine, but you must keep in mind that any property you add to subclasses of your base class, must be nullable. You cannot require something like a DateTime on Business to be required at the database-level, because then you could never save an ApplicationUser, which does not that property. However, this is only an issue at the database-level. You can still use view models to make a particular property on Business required from a front-end perspective.

Is it OK to declare a DBSet in the context for both a base table and a derived table?

I have a SalesOrder table which inherits from a SalesDocument table using Table Per Type Inheritance
The ( simplified) table classes are;
[Table("SalesDocumentHeaders")]
public abstract class SalesDocumentHeader
{
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
[Required]
public int CreatedByUserId { get; set; }
[Required]
public virtual DateTime? DocumentDate { get; set; }
[Required]
public String ReferenceNumber { get; set; }
}
[Table("SalesOrders")]
public class SalesOrder : SalesDocumentHeader
{
[Required]
public String CustomerOrderNumber { get; set; }
public DateTime? DeliverBy { get; set; }
public virtual SortableBindingList<SalesOrderLine> Lines { get; set; }
}
The context contains
public DbSet<SalesOrder> SalesOrders { get; set; }
public DbSet<SalesDocumentHeader> SalesDocumentHeaders { get; set; }
It doesn't strictly need the SalesOrders DBSet, since SalesOrder inherits from SalesDocumentHeader however I find it convenient.
It seems to work OK, but I am worried that there are 2 ways of reaching the same record , am I doing something wrong?
Usually you only need to keep the DBSet for the base table. This helps when you have multiple derived tables (call them A and B) and you need to decide the actual type dynamically.
For example if you have another entity which references type A or B (like a user can have different types of contact information), you can reference the base table and EF will resolve the correct concrete type at runtime. Though of course this adds some extra casting code.

Referencing the creator of a page blog (the connected user) in my entity

I have an entity for my accessing my pages (pages of a blog).
Here it is:
public class Page
{
[Key]
public int PageId { get; set; }
public string AuthorName { get; set; }
[ForeignKey("AuthorName")]
public virtual MembershipUser Author { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public DateTime? PublishDate { get; set; }
public bool Published { get; set; }
public DateTime LastModified { get; set; }
}
As you can see, I would like to keep a reference to the person who created the page (in fact this is the connected user). So I defined an Author member in my class (of type MembershipUser). I also try to define the foreign key but it doesn't work because there is no primary key in the MembershipUser entity. I cannot add one to this entity because if is an aspnet object.
How can I proceed in order to have a reference to the creator of the page in my Page entity?
Thanks.
You can extend the MembershipUser by creating a CustomMembershipUser that will inherit from MembershipUser.
You can add any fields you want to your CustomMembershipUser, you will then also have to create a table of your own with both the original fields and your extra fields.
Here is some documentation that describes how you can do this.
What ORM are you using?
Anyway, you won't be able to reference a class that is not mapped in your ORM. You could create an entity like SystemUser, map it to a table and reference it at your Page entity. When you log in using Membership, you could query that SystemUser and store it in HttpSession so you can use it later.

Resources