我正在开发ASP.NET MVC webapp。我正在使用代码第一种方法。我的模型类是:
public class Post
{
public int PostId { get; set; }
public PostType PostType { get; set; }
public DateTime DateTimeSubmitted { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string CSS { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
}
和
public class Asset
{
public int AssetID { get; set; }
public int PostId { get; set; }
public AssetType AssetType { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Text { get; set; }
public string Path { get; set; }
public string EmbeddedCode { get; set; }
public DateTime DateTimeSubmitted { get; set; }
public string ImageMineType { get; set; }
public Byte[] AssetData { get; set; }
public string CSS { get; set; }
public virtual Post Post { get; set; }
}
我遇到的问题是当我尝试创建Asset
时,只有Asset
。当我想要实现这一点时,也会创建Post
。当我尝试向现有Asset
添加新的Post
时,也会发生同样的情况。
此方法正常(使用Post
创建Asset
):
[HttpPost]
public ActionResult AddPost(InspiredByModel data, HttpPostedFileBase image)
{
Post post = new Post();
Asset asset = new Asset();
if (image != null)
{
asset.ImageMineType = image.ContentType;
asset.AssetData = new byte[image.ContentLength];
image.InputStream.Read(asset.AssetData, 0, image.ContentLength);
}
post.Name = data.Name;
post.Description = data.Description;
asset.DateTimeSubmitted = DateTime.Now;
post.DateTimeSubmitted = DateTime.Now;
post.Assets = new List<Asset>();
post.Assets.Add(asset);
db.Posts.Add(post);
db.SaveChanges();
return View("Index");
}
这不起作用(同时也创建了新Post
,并为新创建的Asset.postId
分配了Post
):
(注意:PostId
是硬编码用于测试目的)
[HttpPost]
public ActionResult AssetUploader(Asset asset, HttpPostedFileBase image)
{
if (image != null)
{
asset.ImageMineType = image.ContentType;
asset.AssetData = new byte[image.ContentLength];
image.InputStream.Read(asset.AssetData, 0, image.ContentLength);
}
var post = db.Posts.Where(p => p.PostId == 1).FirstOrDefault();
asset.DateTimeSubmitted = DateTime.Now;
post.Assets.Add(asset);
db.Entry(post).State = EntityState.Modified;
db.SaveChanges();
return View();
}
我正在为我的问题寻找帮助/解释/解决方案:
Asset
的情况下无法创建新的Post
?Asset
,然后将Post
分配给它吗?Asset
添加/删除Post
?更新:
public class AssetConfiguration : EntityTypeConfiguration<Asset>
{
internal AssetConfiguration()
{
this.HasOptional(i => i.Post)
.WithMany(e => e.Assets)
.HasForeignKey(i => i.PostId);
}
}
public class PostConfiguration : EntityTypeConfiguration<Post>
{
internal PostConfiguration()
{
this.HasOptional(i => i.Assets) ;
}
}
使用这些配置,应用程序的行为仍然相同
答案 0 :(得分:0)
谢谢大家的帮助,问题出在我的代码中。我发布错误的方法。代码工作正常。