使用实体框架的外键存在问题

envsm3lx  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(354)

我使用实体框架,有两个类:

[Table("Client")]
public class Client
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long ClientCode { get; set; }

public string Nombre { get; set; }
}

[Table("Product")]
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string CodProd { get; set; }

[StringLength(80)]
public string NameProd { get; set; 

public Client Client { get; set; };
}

我举了一个新产品的例子:

Product prod = new Product
            {
                CodProd = "Code",
                NameProd = "Name",
                Client = new Client { ClientCode = 12345678 }
            };

db.Products.Add(prod);
db.SaveChanges();

当我添加并保存这个对象时,不会将它记录在数据库中,但是如果我在客户机属性中引用了一个空值的产品,它会出现,但会带有该空值。我不知道为什么会这样。。。

ccgok5k5

ccgok5k51#

假设你们之间有一对多的关系 Client 以及 Product 您的代码应该如下所示:

[Table("Client")]
public class Client
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long ClientCode { get; set; }

    public string Nombre { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

[Table("Product")]
public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string CodProd { get; set; }

    [StringLength(80)]
    public string NameProd
    {
        get; set;
    }

    [ForeignKey("Client")]
    public long ClientCode { get; set; } //foreign key property

    public virtual Client Client { get; set; } //navigation property
}

然后

Product prod = new Product
            {
                CodProd = "Code",
                NameProd = "Name",
                ClientCode = 12345678
            };

db.Products.Add(prod);

相关问题