具有可空值的一对一映射

时间:2015-04-20 11:08:26

标签: c# entity-framework entity-framework-mapping

我有两个实体类ContactUser

UserContactID作为Contact的外键。我可以显示UserContact的关系。

现在我还需要ContactUser关系User表中的相同外键(不在Contact中)

public class Contact{
   public int ContactID {get;set;}
   // This relation doesn't work
   // Need to Make this Work
   public User ContactUser {get;set;}
}

public class User {
   public string Id {get;set;}
   public int? ContactID {get;set;}
   // This Relation works
   [ForeignKey("ContactID")]
   public Contact Contact {get;set;}
}

所以我需要让ContactUser关系适用于Contact。我应该使用什么样的映射?


修改

正如我建议的那样: modelBuilder.Entity<Contact>().HasRequired(c => c.ContactUser).WithOptional(pi => pi.Contact); 我从ForeignKey移除了User属性,导致Multiplicity...error

但我收到的错误如:Invalid column name 'User_Id'.

2 个答案:

答案 0 :(得分:0)

您正在寻找的是

  

一到零或一映射

StackOverflow上有一个很棒的回音。


在您的案例中,显式是必需的:

  • modelBuilder需要WithOptional-Methode

    .WithOptional(pi => pi.Contact);

  • ContactID

  • 的无属性

EF 6.0

的示例
public class Contact
{
    [Key]
    public int ContactId { get; set; }

    public string ContactName { get; set; }
    public User ContactUser { get; set; }
}

public class User
{
    [Key]
    public int UserId { get; set; }

    public string UserName { get; set; }
    public Contact Contact { get; set; }
}

在DbContext-Class中:

public class CodeFirstContext : DbContext
{
    public CodeFirstContext()
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CodeFirstContext>());            
    }

    public DbSet<Contact> Contacts { get; set; }
    public DbSet<User> Users { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
          .HasRequired(co => co.Contact)
          .WithOptional(cu => cu.ContactUser);

        base.OnModelCreating(modelBuilder);
    }
}

在此案例中,现在说User的Contact属性是可选的,并且需要Contact的User属性。 我希望这是您项目的正确星座。

控制台测试

class Program
{
    static void Main(string[] args)
    {
        using (var db = new CodeFirstContext())
        {
            Console.Write("Enter a name: ");
            var name = Console.ReadLine();

            var cont = new Contact { ContactName = name };
            db.Contacts.Add(cont);
            db.SaveChanges();

            var usr = new User { UserName = "MyUsername", Contact = cont };
            db.Users.Add(usr);
            db.SaveChanges();

            var query = from b in db.Contacts
                        orderby b.ContactName
                        select b;

            Console.WriteLine("All contacts in the database:");
            foreach (var item in query)
            {
                Console.WriteLine(item.ContactName);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }
}

答案 1 :(得分:0)

试试这个:

public class Contact
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ContactId { get; set; }

    public string ContactName { get; set; }
    [ForeignKey("ContactId")]
    public User ContactUser { get; set; }
}