简体   繁体   English

实体框架插入记录,其中组合键未插入第二个字段

[英]Entity Framework inserting record with composite key not inserting second field

I am having an issue inserting by child object with Entity Framework 6. 我在使用Entity Framework 6通过子对象插入时遇到问题。

I have two classes: 我有两节课:

public class RoleInstance
{
    [Key, Column(Order = 1)]
    public long RoleId { get; set; }
    [Key, Column(Order = 2)]
    public string EnvirCode { get; set; }

    public int PathId { get; set; }

    public char Published { get; set; }

    [ForeignKey("RoleId")]
    public virtual Role Role { get; set; }
    [ForeignKey("PathId")]
    public virtual RoutingPath RoutingPath { get; set; }
    [ForeignKey("EnvirCode")]
    public virtual Environment Environment { get; set; }

    public ICollection<ActiveDirectoryGroup> ActiveDirectoryGroups { get; set; }
}

public class ActiveDirectoryGroup
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column(Order = 1), Key]
    public long RoleId { get; set; }
    [Column(Order = 2), Key]
    public string EnvirCode { get; set; }
    public string GroupName { get; set; }
    public string GroupGuid { get; set; }
    public char AuditGroup { get; set; }

    [ForeignKey("RoleId,EnvirCode")]
    public virtual RoleInstance RoleInstance { get; set; }
}

I'm trying to insert a record with code like this: 我正在尝试使用以下代码插入记录:

RoleInstance ri = new RoleInstance { RoleId = 1, 
                                     EnvirCode = "ENVIR", 
                                     PathId = 5,
                                     Published = 'Y' 
                                     ActiveDirectoryGroups = new List<ActiveDirectoryGroups>()
}; 

ri.ActiveDirectoryGroups.Add(new ActiveDirectoryGroup() { 
 GroupName = "GROUP NAME", 
 AuditGroup = 'Y'
}; 

_db.Context.Add(ri); 

Then when I save it, it inserts the record into RoleInstance fine the Entity Framework doesn't set the EnvirCode in the ActivityDirectoryGroup . 然后,当我保存它时,它将记录插入RoleInstance因为Entity Framework不会在ActivityDirectoryGroup设置EnvirCode

This is what my modelBuilder looks like: 这是我的modelBuilder样子:

modelBuilder.Entity<ActiveDirectoryGroup>()
            .HasRequired(e => e.RoleInstance)
            .WithMany(e => e.ActiveDirectoryGroups)
            .HasForeignKey(e => new {e.RoleId, e.EnvirCode}); 

A RoleInstance can't have multiple ActiveDirectoryGroups if the key for both is (RoleId,EnvirCode). 如果两者的键都是(RoleId,EnvirCode),则RoleInstance不能有多个ActiveDirectoryGroups。 Switch the key for ActiveDirecoryGroups to Id, or (RoleId,EnvirCode,Id) for a one-to-many relationship. 将ActiveDirecoryGroups的密钥切换为ID,或者将(RoleId,EnvirCode,Id)切换为一对多关系。 And you shouldn't need to mix Fluent and Attribute-based mapping here. 而且您不需要在这里混合Fluent和基于属性的映射。

Here's a working model: 这是一个工作模型:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace Ef6Test
{

    public class Role
    {
        public long RoleId { get; set; }
    }
    public class RoutingPath
    {
        public int RoutingPathId { get; set; }
    }
    public class Environment
    {
        public string EnvironmentId { get; set; }
    }
    public class RoleInstance
    {
        [Key, Column(Order = 1)]
        public long RoleId { get; set; }
        [Key, Column(Order = 2)]
        public string EnvirCode { get; set; }

        public int PathId { get; set; }

        public char Published { get; set; }

        [ForeignKey("RoleId")]
        public virtual Role Role { get; set; }
        [ForeignKey("PathId")]
        public virtual RoutingPath RoutingPath { get; set; }
        [ForeignKey("EnvirCode")]
        public virtual Environment Environment { get; set; }

        public ICollection<ActiveDirectoryGroup> ActiveDirectoryGroups { get; } = new HashSet<ActiveDirectoryGroup>();
    }

    public class ActiveDirectoryGroup
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
        public int Id { get; set; }

        public long RoleId { get; set; }

        public string EnvirCode { get; set; }
        public string GroupName { get; set; }
        public string GroupGuid { get; set; }
        public char AuditGroup { get; set; }

        [ForeignKey("RoleId,EnvirCode")]
        public virtual RoleInstance RoleInstance { get; set; }
    }

    class Db : DbContext
    {

        public DbSet<ActiveDirectoryGroup> ActiveDirectoryGroups { get; set; }
        public DbSet<RoleInstance> RoleInstances { get; set; }


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

    }
    class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {
                db.Database.Initialize(false);

                db.Database.Log = msg => Console.WriteLine(msg);

                RoleInstance ri = new RoleInstance
                {
                    Role = new Role() { RoleId = 1},
                    Environment = new Environment() {  EnvironmentId = "ENVIR" },
                    RoutingPath = new RoutingPath() {  RoutingPathId = 5 },
                    Published = 'Y'
                };

                ri.ActiveDirectoryGroups.Add(new ActiveDirectoryGroup()
                {
                    GroupName = "GROUP NAME",
                    AuditGroup = 'Y'
                });

                db.RoleInstances.Add(ri);
                db.SaveChanges();


            }

            using (var db = new Db())
            {
                foreach (var g in db.ActiveDirectoryGroups)
                {
                    Console.WriteLine($"RoleId: {g.RoleId}, EnvirCode: { g.EnvirCode}");
                }
            }

            Console.ReadKey();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM