[英]How to create relationship between entities & ApplicationUser in MVC 5 EF
If I have a SharedDocument
entity with two properties I want to be related to my ApplicationUser
entity, how do I do this? 如果我有一个具有两个属性的SharedDocument
实体,希望与我的ApplicationUser
实体相关联,该怎么做?
On this MS Tutorial , see if you name the property the same as the PK of the table you want to relate EF can find the relationship pretty easily. 在此MS教程上 ,查看您是否将该属性命名为与要关联的表的PK相同EF可以很容易地找到该关系。 But I have two properties, CreatedBy
& ModifiedBy
that I want related to my User
table but I do not want to name them AspNetUserId
. 但是我有两个属性, CreatedBy
和ModifiedBy
,它们与User
表相关,但我不想将其命名为AspNetUserId
。 How can I do this? 我怎样才能做到这一点?
Model 模型
public class SharedDocumentModel : DbContext
{
public SharedDocumentModel()
: base("MyContext")
{
}
public virtual DbSet<SharedDocument> PortalDocuments { get; set; }
}
public class SharedDocument
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
public DateTime Modified { get; set; }
public virtual ApplicationUser ModifiedBy { get; set; }
public string ContentType { get; set; }
public string FileType { get; set; }
public byte[] FileContent { get; set; }
public double Version { get; set; }
}
}
Error on creating View with Model SharedDocuments 使用模型SharedDocuments创建视图时出错
There was an error running the selected code generator:
'Unable to retrieve metadata for
'MVC.WebSite.Models.SharedDocument'. One or more validation
errors 'mere detected during model generation:
MVC.WebSite.DAL.IdentityUserLogin: EntityType 'IdentityUserLogin'
has no key defined. Define the key for this EntityType.
MVC.WebSite.DAL.IdentityUserRoIe: EntityType 'IdentityUserRoIe' has
no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based
on Vpe 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on
type 'IdentityUserRole' that has no keys defined.
You can do that by adding ForeignKey : 您可以通过添加ForeignKey来做到这一点:
[ForeignKey("CreatedById")]
[ForeignKey("ModifiedById")]
So in you case: 因此,在您的情况下:
public class SharedDocument
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }
public string CreatedById { get; set; }
public DateTime Modified { get; set; }
[ForeignKey("ModifiedById")]
public virtual ApplicationUser ModifiedBy { get; set; }
public string ModifiedById { get; set; }
public string ContentType { get; set; }
public string FileType { get; set; }
public byte[] FileContent { get; set; }
public double Version { get; set; }
}
One more thing: Merge your DbContext
with ApplicationDbContext
and use one database: 还有一件事:将DbContext
与ApplicationDbContext
合并并使用一个数据库:
public class ApplicationUser : IdentityUser
{
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;
}
}
public class SharedDocumentModel : IdentityDbContext<ApplicationUser>
{
public SharedDocumentModel()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public virtual DbSet<SharedDocument> PortalDocuments { get; set; }
public static SharedDocumentModel Create()
{
return new SharedDocumentModel();
}
}
Your error message may be related to referencing ApplicationUser because it is in the IdentityDbContext<ApplicationUser>
context. 您的错误消息可能与引用ApplicationUser有关,因为它位于IdentityDbContext<ApplicationUser>
上下文中。 You can either setup your app context to inherit from the IdentityDbContext<ApplicationUser>
, otherwise you will need to setup a copy of DbSet<ApplicationUser>
in your SharedDocumentModel context. 您可以将应用程序上下文设置为从IdentityDbContext<ApplicationUser>
继承,否则您将需要在SharedDocumentModel上下文中设置DbSet<ApplicationUser>
的副本。
You must match name of FK with property name not property type. 您必须将FK的名称与属性名称而不是属性类型匹配。 So if you have a property with type User
and name CreatedBy
your FK property must CreatedByID
not UserID
. 因此,如果您具有类型为User
且名称为CreatedBy
的属性,则FK属性必须为CreatedByID
而不是UserID
。 Therefore you could simply Add following 2 properties to your SharedDocument
class. 因此,您可以简单地将以下2个属性添加到SharedDocument
类中。
public class SharedDocument
{
public string CreatedByID { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
public string ModifiedByID { get; set; }
public virtual ApplicationUser ModifiedBy { get; set; }
// rest of your code
}
As you can see the type of FK properties are string
since type of ApplicationUser
's PK is string
also. 如您所见,FK属性的类型是string
因为ApplicationUser
的PK的类型也是string
。
But another important issue, it seems you are using Identity's default configuration. 但是另一个重要的问题,似乎您正在使用Identity的默认配置。 If so you already have a DbContext
on your project named ApplicationDbContext
. 如果是这样,您的项目上已经有一个名为ApplicationDbContext
的DbContext
。 Find it and add your other Entities to it. 找到它并向其中添加其他实体。 Don't implement new DbContext
. 不要实现新的DbContext
。
// This class already added to your project
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
// This context already had ApplicationUser set you don't need to add it again
// add your own new entities
public DbSet<SharedDocument> PortalDocuments { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
At the end keep in mind to configuring EF you have 3 option: 最后,请记住配置EF,您有3个选择:
1) Configuration by conventions, as I have done above. 1)按照惯例进行配置,就像我在上面所做的那样。
2) Configuration by Data Annotation. 2)通过数据注释进行配置。 By Adding Attribute to Properties or clasees: 通过向属性或分类添加属性:
[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }
3) Or by fluent API: 3)或通过流利的API:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SharedDocument>()
.HasRequired(e => e.CreatedBy)
.WithMany()
.Map(e => e.MapKey("CreatedByID"));
modelBuilder.Entity<SharedDocument>()
.HasRequired(e => e.ModifiedBy)
.WithMany()
.Map(e => e.MapKey("ModifiedByID"));
}
// rest of code same as before
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.