You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Entity Framework中可空属性无法赋值的问题排查

问题描述

我正在跟随微软的EF教程学习,同时修改数据模型以加深对概念的理解,但编译器似乎不识别我的可空属性。我创建了一个包含Id在内共四个属性的模型,其中最后一个属性为可空类型。在数据库初始化(种子数据)的Initialisation方法中,我尝试创建两个模型实例:一个设置该可空属性的值,另一个忽略该属性,随后使用AddRange方法将它们添加到数据库。但运行dotnet build编译时,出现以下错误:

(filepath)/EntitySQL/Data/DBInitialiser.cs(22,45): error CS1513: } expected [(filepath)/EntitySQL/EntitySQL.csproj]

当我注释掉该可空属性的赋值语句后,这个错误以及其他16个语法错误全部消失!请问如何为这个可空对象赋值?

相关代码如下:

EntitySQL/Models/Article.cs

namespace EntitySQL.Models;

public class Article
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> Paragraphs { get; set; }
    public ICollection<Video>? Videos { get; set; }     
}

EntitySQL/Models/Video.cs

public class Video
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Link { get; set; }
}

EntitySQL/Data/DBInitialiser.cs

using EntitySQL.Models;

namespace EntitySQL.Data
{
    public static class DBInitialiser
    {
        public static int Initialise(NewsContext context)
        {
            if (context.Articles.Any() || context.Videos.Any())
            {
                return 0;
            }
            
            Video video1 = new Video { Name = "Cat video", Link = "youtube cat videos.commm" }; //This link is fake
            Video video2 = new Video { Name = "Big Cat video", Link = "meowtube.com" }; //This link is fake
            
            Article bigCat = new Article 
                                 {
                                     Name = "World's Biggest Cat Spotted Outside McDonalds", 
                                     Paragraphs = new List<String>
                                                  {
                                                      "Residents said that the apocalypse was coming.",
                                                      "At about 3am this morning, locals were woken up to what sounded like an earthquake, as a cat-like animal was seen playing with the street lights as a toy.",
                                                      "The animal was about 6 metres tall and 30 metres long, filling up the entire carpark at McDonalds CityVille. Workers were terrified and police were called in to help though, understandably, they were clueless as to how to contain the furry beast."
                                                  },
                                     Videos = new List<Video>{ video1, video2 }; //This line is the problem!
                                };
            
            Article turtleHatch = new Article {
                Name = "A Turle Hatched",
                Paragraphs = new List<String>{
                    "Yesterday, at Snow White Beach, residents were treated to one of the most adorable sights some have ever seen",
                    "Two baby turtles were flapping their flippers on top of each other as they pushed with all of their might to reach the ocean",
                    "Despite the unusual time, the birds were successfully fended of by beachgoers who cheered as the turtles made it all the way to the ocean."
                }
            };
                        
            context.Articles.AddRange(new List<Article> { bigCat, turtleHatch });
            context.SaveChanges();

            return 0;
        }
        
        public static int CreateDbIfNotExists(this IHost host)
        {
            using (IServiceScope scope = host.Services.CreateScope())
            {
                IServiceProvider provider = scope.ServiceProvider;
                NewsContext context = provider.GetRequiredService<NewsContext>();
                context.Database.EnsureCreated();
                Initialise(context);
            }

            return 0;
        }
    }
}
解决方案

编译错误的核心原因是对象初始化器中属性赋值语句末尾误用了分号,而非逗号。在C#的对象初始化语法里,多个属性之间需要用逗号分隔,最后一个属性可省略逗号,但绝对不能用分号——分号会提前终止初始化器,导致编译器找不到闭合的},从而抛出CS1513错误。

修正后的bigCat对象初始化代码如下:

Article bigCat = new Article 
{
    Name = "World's Biggest Cat Spotted Outside McDonalds", 
    Paragraphs = new List<String>
    {
        "Residents said that the apocalypse was coming.",
        "At about 3am this morning, locals were woken up to what sounded like an earthquake, as a cat-like animal was seen playing with the street lights as a toy.",
        "The animal was about 6 metres tall and 30 metres long, filling up the entire carpark at McDonalds CityVille. Workers were terrified and police were called in to help though, understandably, they were clueless as to how to contain the furry beast."
    },
    Videos = new List<Video>{ video1, video2 } // 将分号改为逗号(或直接省略,因是最后一个属性)
};

另外补充两个潜在优化点:

  • Name、Link等string属性未标记可空(?),在C# 8+默认启用可空上下文的情况下会触发警告。若这些属性允许为空,可添加?;若必须非空,建议在构造函数中初始化或使用required关键字。
  • 初始化List时可直接用集合初始化器,无需显式调用new List<T>{...}(当前写法合法,但简化写法更简洁)。

内容的提问来源于stack exchange,提问作者JD9999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:11:01