与使用新的导航属性的实体框架添加新实体 [英] Adding New Entity with New Navigation Property Using Entity Framework

查看:231
本文介绍了与使用新的导航属性的实体框架添加新实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类模型允许我一个特征图像添加到ProductType实体。个人ProductType类的定义标识它引用的特定影像HomePageImageId和HomePageImage导航属性。



我有一个图片类定义,其中包含所有的图像(即,宽度,高度,格式类型,名称等)的元信息。



我也有一个的ImageData类定义包含实际图像数据。这个拥有FK关系,它是通过上述的图像类中可用的元信息。



因此,这里的EF实体是什么样子。

  [DataContract] 
表(ProductTypes)]
公共类产品型号:IEntity
{
[重点]
[数据成员]
[专栏(ID)]
公众的Int64标识{搞定;组; }

[数据成员]
[数据类型(DataType.Text)
[列(名称)]
公共字符串名称{;组; }

[数据成员]
[数据类型(DataType.MultilineText)
[列(说明)
公共字符串描述{搞定;组; }

[数据成员]
[数据类型(DataType.MultilineText)
[列(节选)]
公共字符串摘录{搞定;组; }

[数据成员]
[列(ImageId)]
公众的Int64? ImageId {搞定;组; }

[ForeignKey的(ImageId)]
公共虚拟图像HomePageImage {搞定;组; }

}


[DataContract]
表(图像)]
公共类图片:IEntity
{
[关键]
[数据成员]
[专栏(ID)]
公众的Int64标识{搞定;组; }

[数据成员]
[列(名称)]
[数据类型(DataType.Text)
公共字符串名称{;组; }

// Addt'l性能删除

[数据成员]
[列(数据ID)]
公众的Int64 DATAID {搞定;组; }


#地区的导航属性

[ForeignKey的(数据ID)]
公共虚拟的ImageData的ImageData {搞定;组; }

#endregion

}


[DataContract]
表(的ImageData)]
酒店的公共类的ImageData:IEntity
{
[键,ForeignKey的(图像)]
[数据成员]
[专栏(ID)]
公众的Int64标识{搞定;组; }

[列(数据)]
[MAXLENGTH]
[数据类型(DataType.Upload)
公共字节[] {数据获取;组; }

公共虚拟图片图片{搞定;组; }

}

结构上这一切看起来不错。问题是,当我要添加新的图像我收到以下错误。

  A外键值无法插入,因为相应的主键值不存在。 [外键约束名称=的ImageData] 



我理解错误。我只是不知道为什么它的发生。资源库中的AddImage方法看起来像下面的代码片段里的图像参数不仅包含图像元数据,但它的ImageData属性,它已成功地填充的ImageData中包含图像的字节[]信息的实例。每个实体是新的,都为0

 公共静态图像AddImage(形象画像)
{$ B $标识的b图像RET = NULL;
使用(上下文CTX =新的上下文())
{
图像RET = ctx.Images.Add(图片);
ctx.SaveChanges();
}
返回RET;
}



我本来期望,自的ImageData的实例已经被分配给导航属性的加入将管理两者之间的关系,将它们插入和更新密钥作为neeccessary。至少,这就是我看到它在过去的工作。



这是接近的这个帖子但如果他是指现有的实体,我希望创建两个新的实体。



有人能看到什么我在这里丢失?



更新2013年11月5日



我有浓缩的代码行数更少有望缩小聚光灯的问题...
我仍​​然收到错误。

 使用(上下文CTX =新的上下文())
{
//
//初始化一个ProductType实例。
ProductType productType = ProductRepository2.GetProductType(CTX,productTypeId);
productType.Description = txtDescription.Text.Trim();
productType.Excerpt = txtDescription.Text.Substring(?0,(txtDescription.Text.Trim()长度和小于100)txtDescription.Text.Trim()长度:100);

//
//如果图像上传然后初始化图像的DTO
如果(fileUpload.FileBytes.Length大于0)
{
的ImageData imgData =新的ImageData {数据= fileUpload.FileBytes};
productType.HomePageImage = Infrastructure.Utils.ImageUtils.GetPostedImage(fileUpload.PostedFile);
productType.HomePageImage.ImageData = imgData;
productType.HomePageImage.DateAdded = DateTime.Now;
productType.HomePageImage.DateUpdated = DateTime.Now;
}
ctx.SaveChanges();
}


解决方案

我在这里做的是我创建一个ProductTpe对象和图像对象ProductType对象分配给HomePageImage财产,当我添加ProductType对象在上下文中ProductTypes并调用调用SaveChanges()方法,它会创建数据库的ImageData,图片和ProductType。

  ProductType prodObj =新ProductType 
{
NAME =名,
说明=说明,
摘录=摘录,
图像=新的图像//你可以直接给你的图像对象这里
{
NAME =名,
的ImageData =新的ImageData
{
数据=新的字节[0]; //使用您的数据
}
}
};

使用(上下文CTX =新的上下文())
{
ctx.ProductTypes.add(prodObj);
ctx.saveChanges();
返回prodObj;
}


I have a class model allows me to add a feature Image to a ProductType entity. The individual ProductType class definition identifies a HomePageImageId and HomePageImage navigation property which references a specific Image.

I have an Image class definition which contains all the META information for an image (i.e. width, height, format type, name, etc.).

I also have an ImageData class definition which contains the actual image data. This possesses a FK relationship to it's meta information available via the aforementioned Image class.

So here's what the EF Entities look like.

[DataContract]
[Table("ProductTypes")]
public class ProductType : IEntity
{
    [Key]
    [DataMember]
    [Column("Id")]
    public Int64 Id { get; set; }

    [DataMember]
    [DataType(DataType.Text)]
    [Column("Name")]
    public String Name { get; set; }

    [DataMember]
    [DataType(DataType.MultilineText)]
    [Column("Description")]
    public String Description { get; set; }

    [DataMember]
    [DataType(DataType.MultilineText)]
    [Column("Excerpt")]
    public String Excerpt { get; set; }

    [DataMember]
    [Column("ImageId")]
    public Int64? ImageId { get; set; }

    [ForeignKey("ImageId")]
    public virtual Image HomePageImage { get; set; }

}


[DataContract]
[Table("Images")]
public class Image : IEntity
{
    [Key]
    [DataMember]
    [Column("Id")]
    public Int64 Id { get; set; }

    [DataMember]
    [Column("Name")]
    [DataType(DataType.Text)]
    public String Name { get; set; }

    // Addt'l properties removed 

    [DataMember]
    [Column("DataId")]
    public Int64 DataId { get; set; }


    #region Navigation Properties

    [ForeignKey("DataId")]
    public virtual ImageData ImageData { get; set; }

    #endregion

}


[DataContract]
[Table("ImageData")]
public class ImageData : IEntity
{
    [Key, ForeignKey("Image")]
    [DataMember]
    [Column("Id")]
    public Int64 Id { get; set; }

    [Column("Data")]
    [MaxLength]
    [DataType(DataType.Upload)]
    public byte[] Data { get; set; }

    public virtual Image Image { get; set; } 

}

Structurally this all looks good. The problem is that when I want to ADD a new image I am getting the following error.

A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = ImageData ]

I understand the error. I am just not sure why it's occurring. The AddImage method in the repository looks like the following code snippet where the "image" parameter contains not only the Image meta data, but its ImageData property which has been successfully populated with an instance of ImageData containing the byte[] information for an image. Each entity is new and have Id's of 0.

    public static Image AddImage(Image image)
    {
        Image ret = null;
        using(Context ctx = new Context())
        {
            Image ret = ctx.Images.Add(image);
            ctx.SaveChanges();
        }
        return ret;
    }

I would have expected that since an instance of ImageData has been assigned to the Navigation property that the ADD would manage the relationships between the two, inserting them and updating the Keys as neeccessary. At least that's how I have seen it work in the past.

It's close to this post but where he is referring to an existing entity I am looking to create both as new entities.

Can anyone see what I am missing here?

UPDATE 11/05/2013

I have condensed the code to fewer lines to hopefully narrow the spotlight on the issue ... I am still receiving the error.

        using (Context ctx = new Context())
        {
            //
            // Initialize a ProductType instance.
            ProductType productType = ProductRepository2.GetProductType(ctx, productTypeId);
            productType.Description = txtDescription.Text.Trim();
            productType.Excerpt = txtDescription.Text.Substring(0, (txtDescription.Text.Trim().Length < 100) ? txtDescription.Text.Trim().Length : 100);

            //
            // If an image was uploaded then initialize the Image DTOs
            if (fileUpload.FileBytes.Length > 0)
            {
                ImageData imgData = new ImageData { Data = fileUpload.FileBytes };
                productType.HomePageImage = Infrastructure.Utils.ImageUtils.GetPostedImage(fileUpload.PostedFile);
                productType.HomePageImage.ImageData   = imgData;   
                productType.HomePageImage.DateAdded   = DateTime.Now;
                productType.HomePageImage.DateUpdated = DateTime.Now;
            }
            ctx.SaveChanges();
        }

解决方案

What I do here is I create a ProductTpe object and assign Image object to HomePageImage property in ProductType object and when I add ProductType object to ProductTypes in context and call saveChanges() method, It will create ImageData, Image and ProductType in DB.

ProductType prodObj = new ProductType
{
    Name="name",
    Description= "description",
    Excerpt ="excerpt",
    Image= new Image //you can directly assign your image object here
    {
        Name="name",
        ImageData=new ImageData
        {
            Data=new byte[0]; //use your data
        }
    }
};

using(Context ctx = new Context())
{
    ctx.ProductTypes.add(prodObj);
    ctx.saveChanges();
    return prodObj;
}

这篇关于与使用新的导航属性的实体框架添加新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆