Entity framework 5 实体框架代码优先方法

Entity framework 5 实体框架代码优先方法,entity-framework-5,Entity Framework 5,我使用EntityFramework codefirst方法。我的编码是 class Blog { [Key] public int BlobId { get; set; } public string Name { get; set; } public virtual List<Post> Posts { get; set; } } class Post { [Key] public int PostId { get; set; }

我使用EntityFramework codefirst方法。我的编码是

class Blog
{
    [Key]
    public int BlobId { get; set; }
    public string Name { get; set; }
    public virtual List<Post> Posts { get; set; }
}

class Post
{
    [Key]
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlobId { get; set; }
    public virtual Blog Blob { get; set; }
}

class BlogContext:DbContext
{
    public BlogContext() : base("constr") { }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
      using (var db = new BlogContext())
        {
            Console.WriteLine("Enter a name for a new blob:");
            var name = Console.ReadLine();
            var b = new Blog { Name = name };
            db.Blogs.Add(b);
            db.SaveChanges();
在这里,我在blogtable中添加了名称

            Console.WriteLine("Enter Title:");
            var title = Console.ReadLine();
            Console.WriteLine("Enter Content");
            var content = Console.ReadLine();
            var c = new Post { Title = title, Content = content, BlobId = id1};
            db.Posts.Add(c);
            db.SaveChanges();
现在使用Name am获取blogs表的blogid

            Console.WriteLine("Enter Title:");
            var title = Console.ReadLine();
            Console.WriteLine("Enter Content");
            var content = Console.ReadLine();
            var c = new Post { Title = title, Content = content, BlobId = id1};
            db.Posts.Add(c);
            db.SaveChanges();
我在这里读取标题、内容的数据。然后将标题、内容和blogid(我从另一个表获得)添加到Posts表中

            Console.WriteLine("Enter Title:");
            var title = Console.ReadLine();
            Console.WriteLine("Enter Content");
            var content = Console.ReadLine();
            var c = new Post { Title = title, Content = content, BlobId = id1};
            db.Posts.Add(c);
            db.SaveChanges();
我在BlobId=id1时出错

Am GET无法将类型“System.Linq.IQueryable”隐式转换为“int”此错误

         }
         Console.ReadLine();
     }
}

你能帮我解决这个问题吗?如果你不理解我解释的内容,请回答我

以下查询是一个元素序列,而不是标量值,即使你认为只有一个结果,但当查询结果被迭代时,它仍然是一个包含一个元素的集合:

var id1 = from val in db.Blogs
         where val.Name == name
         select val.BlobId;
将此更改为:

int id1 = (from val in db.Blogs
         where val.Name == name             
         select val.BlobId).First();

此查询将立即执行并返回序列中的第一个元素。如果没有匹配项,它将引发异常,因此您可能希望使用
FirstOrDefault
并将其分配给可为空的int。

非常感谢,我得到了它。您告诉我“元素序列”,但在收到id后,我尝试打印它,但只得到了1个值。您能澄清一下吗,第二个查询将返回查询的第一个结果(一个整数),您不希望这样吗?你把这个int赋值给BlobId属性,这个属性也是int,所以我觉得它是正确的。