本文介绍了实体框架中的1:1关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在实体框架中 ApplicationUser 和我自己的类之间的1:1关系。

I need 1:1 relationship between ApplicationUser and my own class in entity framework.

我这样做:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }

    /*Realations*/

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Posts Post { get; set; }
}


public class Posts : System.Object
{
    public Posts()
    {
        this.PostDate = DateTime.Now;
        this.PostViews = 0;
        this.PostPic = "d.jpg";
    }

    [Key]
    public int PostID { get; set; }

    public string PostName { get; set; }
    public string PostSummery { get; set; }
    public string PostDesc { get; set; }
    public string PostPic { get; set; }
    public DateTime PostDate { get; set; }
    public int PostViews { get; set; }
    public string postMetaKeys { get; set; }
    public string PostMetaDesc { get; set; }


    public string UserId { get; set; }
    [Key, ForeignKey("UserId")]
    public virtual ApplicationUser ApplicationUser { get; set; }


    public int CategoryID { get; set; }
    [Key, ForeignKey("CategoryID")]
    public virtual Categories Category { get; set; }

    public virtual ICollection<Comment> commnets {get; set;}
}

但是当我写命令add -migration关系在 Nuget 控制台内。

But I am getting an exception when I write the command "add-migration relation" inside Nuget console.

我还在 IdentityModels 中添加以下代码,但是显示了另一个错误:

I also add below code inside IdentityModels, but another error was shown:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);


        modelBuilder.Entity<ApplicationUser>()
        .HasOptional(f => f.Post)
        .WithRequired(s => s.ApplicationUser);
    }



ApplicationUser_Post_Target::在ApplicationUser_Post关系中的角色
'ApplicationUser_Post_Target'中,多项式无效。
由于从属角色属性不是关键属性,因此从属角色的多重性的
上界必须为'*'。

ApplicationUser_Post_Target: : Multiplicity is not valid in Role 'ApplicationUser_Post_Target' in relationship 'ApplicationUser_Post'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

有什么问题?

推荐答案

你想要1到1的用户和帖子之间的关系?一个用户只能发布一个而且只发布?

you want a 1 to 1 relation between user and post ? A user can only post one, and only, post ?

无论如何,在EF(至少6)中,可以在共享相同的两个实体之间建立1到1的关系PK。那就是PK是FK。所以你必须将帖子的PK设置为一个字符串。

Anyway, in EF (at least 6) a 1 to 1 relation can be established between two entities sharing the same PK. That is the PK is the FK. So you must set the PK of posts as a string.

否则你处于1到*关系。

Otherwise you are in a 1 to * relation.

这篇关于实体框架中的1:1关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 22:13