实体框架代码第一种方法

时间:2013-04-12 09:27:06

标签: 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; }
    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();

直到这一步,我在我的SQlserver中创建了两个表(博客和帖子).BlobId是博客表中的主键。帖子表中的外键。博客表中的博客是自动递增的。帖子在帖子中表格也会自动递增

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();

我在博客表中添加了名称

             var id1 = from val in db.Blogs
             where val.Name == name
             select val.BlobId;

现在使用Name am获取博客表的博客

            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

时遇到错误

得到无法将类型'System.Linq.IQueryable'隐式转换为'int'此错误

         }
         Console.ReadLine();
     }
}

你能帮我解决一下。如果你不明白我的解释,请回复我

1 个答案:

答案 0 :(得分:0)

以下查询是一系列元素,而不是标量值,即使您认为只有一个结果,当迭代查询结果时,它仍然是具有一个元素的集合:

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。

相关问题