小编M K*_* II的帖子

实体框架添加如果没有更新则不存在

我喜欢AddOrUpdate让你指定一个过滤器来检查以避免添加重复项.但我想要没有更新的类似功能.

现在我做这样的事情:

var checkProfile = from p in db.Profile
    where p => p.LastName == newProfile.lastName
         && p => p.FirstName == newProfile.firstName
         && p => p.Middle== newProfile.middle
    select p;
if (checkProfile.FirstOrDefault() == null)
{
    db.Profile.Add(newProfile);
    db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

db.Profile.AddOrUpdate(p => new {p.LastName, p.FirstName, p.Middle}, newProfile);
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

但我宁愿在这种情况下跳过修改数据.

第一个例子做了我想要的,但有更多的代码.在第一个例子中是否有更简单/更清洁的方式来做我想要的事情?

更新:

我喜欢Ognyan Dimitrov的建议.我正在努力实现它.我的模型继承自BaseEntity.我可以在那里放一个通用版本吗?

我的模型定义如下:

public class Address :BaseEntity
{
Run Code Online (Sandbox Code Playgroud)

我的BaseEntity:

public class BaseEntity 
{
    public virtual T AddIfNotExists<T>(T entity, Expression<Func<T, bool>> predicate = null)
    {
        var exists = predicate != null ? DbSet.Any(predicate) …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework

32
推荐指数
4
解决办法
5万
查看次数

Automapper说Mapper.Map是过时的全局映射?

我在我的项目中定义了一个全局的Automapper配置,允许我Mapper.Map<targetType>(sourceObject);在我的代码中使用.(参见下面的配置.)

我更新了NuGet包,我看到了Mapper.Map已经过时/折旧的消息.我在GitHub上回到Automapper,看到这样的例子:

[Test]
public void Example()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Source1, SubDest1>().FixRootDest();
        cfg.CreateMap<Source2, SubDest2>().FixRootDest();
    });

    config.AssertConfigurationIsValid();

    var mapper = config.CreateMapper();

    var subDest1 = mapper.Map<Source1, SubDest1>(new Source1 {SomeValue = "Value1"});
    var subDest2 = mapper.Map<Source2, SubDest2>(new Source2 {SomeOtherValue = "Value2"});

    subDest1.SomeValue.ShouldEqual("Value1");
    subDest2.SomeOtherValue.ShouldEqual("Value2");
}
Run Code Online (Sandbox Code Playgroud)

我是否必须在使用映射的EVERY方法中创建配置?

我目前的全局配置:

namespace PublicationSystem.App_Start
{
    public class AutoMapperConfig
    {
        public static void CreateMaps()
        {
            CreateProjectMaps();
        }

        private static void CreateProjectMaps()
        {
            Mapper.CreateMap<Project, ProjectCreate>();
            Mapper.CreateMap<Project, ProjectSelectable>();
            //...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:感谢Scott Chamberlain的一些指导,我创建了一个这样的课程:

    public …
Run Code Online (Sandbox Code Playgroud)

c# automapper

25
推荐指数
3
解决办法
4万
查看次数

SSRS报告定义比服务器更新

我在Visual Studio 2015中创建了一些包含所有最新更新的报告.但是,当我尝试部署报告时,我收到以下消息:

此版本的Reporting Services无效或支持此报告的定义.
11:40:28错误
报表定义可能是使用更高版本的Reporting Services创建的,或者包含的内容不是
11:40:28错误
格式正确或基于Reporting Services架构无效.详细信息:报表定义具有无效目标
11:40:28错误
名称空间' http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition '无法升级.

.rdl文件的第一行设置如下:

<?xml version="1.0" encoding="utf-8"?>
<Report MustUnderstand="df" 
xmlns="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" 
xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" 
xmlns:df="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition/defaultfontfamily">
Run Code Online (Sandbox Code Playgroud)

我可以更改架构定义吗?如果是这样,到底是什么?我尝试过将2016年改为2014年或2012年,但都没有奏效.

我可以去看看有效的定义吗?

sql-server reporting-services ssrs-2012

24
推荐指数
6
解决办法
5万
查看次数

为什么C#Math.Ceiling向下舍入?

我有一个艰难的一天,但有些事情没有正确加起来.

在我的C#代码中,我有这个:

Math.Ceiling((decimal)(this.TotalRecordCount / this.PageSize))
Run Code Online (Sandbox Code Playgroud)

其中(int)TotalRecordCount= 12和(int)PageSize= 5.我得到的结果是2.
(两个值都是int值.)

根据我的计算,12/5 = 2.4.我以为Math.Ceiling会一直围着,在这种情况下,给我3?

PS,如果我这样做:

Math.Ceiling(this.TotalRecordCount / this.PageSize)
Run Code Online (Sandbox Code Playgroud)

我收到消息:

Math.Ceiling(this.TotalRecordCount/this.PageSize)
以下方法或属性之间的调用不明确:
'System.Math.Ceiling(decimal)'和'System.Math.Ceiling(double)'

c# math

9
推荐指数
2
解决办法
2175
查看次数

PluralizationServices将状态更改为Statu

我们有一个T4模板System.Data.Entity.Design.PluralizationServices用于处理某些模型生成的表名.

当我们Status在名称中运行一个表时,例如CompanyStatus,该Singularize方法返回CompanyStatu.我在下面有一些示例代码.

如何正确查看CompanyStatus?

void Main()
{
    // Sanity checks
    Console.WriteLine(Singularize("Cats"));
    Console.WriteLine(Singularize("Cat"));
    Console.WriteLine(Singularize("Status"));
    // The real issue
    Console.WriteLine(Singularize("CompanyStatus"));
}

static string Singularize(string word)
{
    var singularword = System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(System.Globalization.CultureInfo.GetCultureInfo("en-us")).Singularize(word);
    return singularword;
}
Run Code Online (Sandbox Code Playgroud)

返回:

Cat
Cat
Status
CompanyStatu

我也尝试过:

static string Singularize(string word)
{
    var pluralizationService = System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(System.Globalization.CultureInfo.GetCultureInfo("en-us"));
    ((ICustomPluralizationMapping)pluralizationService).AddWord("companystatus", "companystatuses");
    var singularword = pluralizationService.Singularize(word);      
    return singularword;
}
Run Code Online (Sandbox Code Playgroud)

c# pluralize

9
推荐指数
1
解决办法
372
查看次数

MVC应用程序不使用通用方法运行

我想在我的Base控制器中创建一个方法,该方法将获取一个列表并将其作为SelectList返回.我写了一个方法,网站编译,但我得到这个消息:

无法1[System.Web.Mvc.SelectListItem] GetSelectList[T](System.Collections.Generic.IEnumerable在控制器'PublicationSystem.Controllers.BaseController'上调用操作方法'System.Collections.Generic.IEnumerable 1 [T],System.String,System.String,System.String,System.Object)'因为action方法是通用的方法.
参数名称:methodInfo

我想知道我做错了什么.这是代码:

public partial class BaseController : Controller
{
    public IEnumerable<SelectListItem> GetSelectList<T>
    (
        IEnumerable<T> itemList, 
        string textField,
        string valueField,
        string defaultPrompt = "", 
        object defaultValue = null)
    {
        IEnumerable<SelectListItem> returnList = null;

        if (!string.IsNullOrEmpty(defaultPrompt))
        {
            returnList = Enumerable.Repeat(
                new SelectListItem { Value = (string)defaultValue, Text = defaultPrompt },
                count: 1);
        }

        var textProp = typeof (T).GetProperty(textField);
        var valueProp = typeof (T).GetProperty(valueField);

        returnList = returnList.Concat
            (itemList
                .Select(x =>
                    new SelectListItem
                    {
                        Value = Convert.ToString(valueProp.GetValue(x)), …
Run Code Online (Sandbox Code Playgroud)

c# generics asp.net-mvc

6
推荐指数
1
解决办法
3339
查看次数

使用 HttpClient.GetAsync 调用 Web API 似乎挂了

我正在研究概念原型的证明。
我有 Asp.Net C# web 表单(Visual Studio 2013,.Net 4.5)页面。单击按钮时,我会执行以下操作:

List<Blog> blogs = null;
protected void btnLoadData_Click(object sender, EventArgs e)
{
    //...;

    switch (int.Parse(rblDataSource.SelectedValue))
    {
        //...;

        case 4:
            RunAsyncBlogs().Wait();

            break;

        default:
            blogs = localGetter.GetBlogs();
            break;
    }

    //...;
}
Run Code Online (Sandbox Code Playgroud)

RunAsyncBlogs 看起来像这样:

static async Task RunAsyncBlogs()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost/wapiDemo/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP GET
        HttpResponseMessage response = await client.GetAsync("api/Blogs");
        if (response.IsSuccessStatusCode)
        {
            List<Blog> thisBlogList = await response.Content.ReadAsAsync<List<Blog>>();
            var cnt = thisBlogList.Count();
        }

    } …
Run Code Online (Sandbox Code Playgroud)

c# asp.net task-parallel-library async-await asp.net-web-api

5
推荐指数
1
解决办法
1万
查看次数

Code First从int迁移到Guid主键问题

我正在尝试将我的代码第一个ID列从"int"更改为"Guid",并且在尝试运行迁移时,我收到消息:

Identity column 'CustomFieldId' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.
Run Code Online (Sandbox Code Playgroud)

我正在定义这样的列:

public partial class CustomField : BaseEntity
{

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid CustomFieldId { get; set; }
Run Code Online (Sandbox Code Playgroud)

在CustomFieldMapping.cs中映射它,如下所示:

public CustomFieldMapping()
{
    //Primary key
    HasKey(t => t.CustomFieldId);

    //Constraints 
    Property(t => t.CustomFieldId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Run Code Online (Sandbox Code Playgroud)

并且生成的迁移正在尝试执行此操作:

public override void Up()
{
    DropForeignKey("dbo.CustomField", "CustomFormId", "dbo.CustomForm");
    DropForeignKey("dbo.CustomData", "CustomFieldId", "dbo.CustomField");
    DropForeignKey("dbo.CustomForm", "ParentFormId", "dbo.CustomForm");
    DropIndex("dbo.CustomField", new[] { "CustomFormId" });
    DropIndex("dbo.CustomForm", new[] { …
Run Code Online (Sandbox Code Playgroud)

entity-framework-6

5
推荐指数
1
解决办法
4559
查看次数

如何在LINQPad中模拟ConfigurationManager

我正在尝试在LINQPad中测试一些代码.但是,base该类调用Configuration Manager.在LINQPad中进行测试时,如何模拟它.

void Main()
{
    var tRepo = new TestRepository();
    var result = tRepo.GetAsync(1);
    result.Dump();
}

public partial class TestRepository : BaseRepository<Customer>, ICustomerRepository 
{
    // Here base throws the errror
    public TestRepository() : base("DbConnString")
    {            
    }
}
Run Code Online (Sandbox Code Playgroud)

这是BaseRepository的构造函数(来自已编译的DLL,因此在LINQPad中不可编辑):

protected BaseRepository(string connectionStringName)
{
    var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName];

    Connection = new SqlConnection(connectionString.ConnectionString);
    Connection.Open();
}
Run Code Online (Sandbox Code Playgroud)

c# linqpad

5
推荐指数
1
解决办法
1459
查看次数

我们可以使用 SonarLint 忽略特定的 S100 警告吗

在我们的 C# 项目中,我们使用 SonarQube/SonarLint。

我们有一个名为 的属性DMSCodeDMS是我们在组织中使用的缩写,因此确实有效。然而 SonarLint 发出了 S100 警告。

有没有办法忽略此代码:

public string DMSCode { get; set; }
Run Code Online (Sandbox Code Playgroud)

我尝试搜索“sonarlint s100ignore”和其他一些变体,但什么也没找到。

sonarqube sonarlint

5
推荐指数
1
解决办法
3191
查看次数