-
C#
- Common
-
EntityFramework
- EF删除带有one-to-many relationship记录时失败。
- 怎么启用关联表中的关联表eagerloading.
EF
删除RelatedMember
再新增, 出现异常conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
- Entities in 'Y' participate in the 'FK_Y_X' relationship. 0 related 'X' were found. 1 'X' is expected
ERROR 1452 : Cannot add or update a child row: a foreign key constraint fails
- EF使用MySQL数据库
- 从 datetime2 数据类型到 datetime 数据类型的转换产生一个超出范围的值
- EF设置数据库更新方式
- Reading Related Data with the Entity Framework in an ASP.NET MVC Application
- cascade deletes 联级删除
- 解决EntityFrameworkCore “无法将“Add-Migration”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。”
- EntityFramework在使用Include方法时发生FormatException:该字符串未被识别为有效的布尔值。
- Pomelo v2.0.1在EntityFrameworkCore v2.1.0下迁移数据库抛出
Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalParameterBuilder..ctor(Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)'.
- WebApi
- JSON
- Web
C#
Common
.net framework项目使用net standard 包报NotFileFoundException.
答:
原因:由于旧的项目文件无法通过net standard的包引用方式找到包的位置。
解决方法:在项目的.csproj文件的第一个<PropertyGroup>
下加上<RestoreProjectStyle>PackageReference</RestoreProjectStyle> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
即可。
Check if Object is Dictionary or List
答:
public bool IsList(object o)
{
if(o == null) return false;
return o is IList &&
o.GetType().IsGenericType &&
o.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>));
}
public bool IsDictionary(object o)
{
if(o == null) return false;
return o is IDictionary &&
o.GetType().IsGenericType &&
o.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>));
}
Visual Studio 2017 使用 C#7.2, build成功,发布时跳过。
问题细节:
已将项目中属性中语言版本改为7.2.
问题原因:
发布的配置和build配置不同步,导致发布时的语言版本还是以前的版本。
解决方案:
- 找到文件路径
properties>PublishProfiles>{{你的发布配置文件名}}.pubxml
- 添加
<LangVersion>latest</LangVersion>
, 总是保持发布时的语言版本为最新。
EntityFramework
EF删除带有one-to-many relationship记录时失败。
答:EF 默认one-to-many是将外键模式设为严格模式, 导致必须清除关联的子表,才能删除父表。
怎么启用关联表中的关联表eagerloading.
答:For EF 6
using System.Data.Entity;
query.Include(x => x.Collection.Select(y => y.Property))
See Remarks for more examples.
Make sure to add using System.Data.Entity;
to get the version of Include
that takes in a lambda.
If you are using EF Core you can use the new method ThenInclude
query.Include(x => x.Collection)
.ThenInclude(x => x.Property);
EF
删除RelatedMember
再新增, 出现异常conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
答:
DbContext.Entry(updated).State = EntityState.Added;
if(existing != null)
{
var exist = DbContext.Set<TKey>().Find(existing.Id);
if (exist != null)
{
DbContext.Entry(exist).State = EntityState.Detached;
}
DbContext.Entry(exist).State = EntityState.Deleted;
}
Entities in 'Y' participate in the 'FK_Y_X' relationship. 0 related 'X' were found. 1 'X' is expected
答:one to many relationship, the foreign key don't use not null
ERROR 1452 : Cannot add or update a child row: a foreign key constraint fails
答: 由于在设置外键的时候, 外键对应的字段已存在且在主表找不到对应的数据。
EF使用MySQL数据库
答:msdn答案。
从 datetime2 数据类型到 datetime 数据类型的转换产生一个超出范围的值
答:由于datetime2范围是"0001-01-01 到 9999-12-31",datetime的日期范围是:”1753 年 1 月 1 日到 9999 年 12 月 31 日“
EF设置数据库更新方式
答:在global.asax中设置Database.SetInitializer<MyOAContext>(setting)
,setting有两个选项DropCreateDatabaseAlways
,DropCreateDatabaseIfModelChanges
,``
Reading Related Data with the Entity Framework in an ASP.NET MVC Application
答:use eager loading.
cascade deletes 联级删除
答: ctx.Parent.Remove(parent)
;
关闭cascade deletes:
public class SchoolContext<: DbContext
{
public SchoolContext():base("MySchool")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasOptional<Standard>(s => s.Standard)
.WithMany()
.WillCascadeOnDelete(false);
}
}
解决EntityFrameworkCore “无法将“Add-Migration”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。”
答:
Import-Module {项目目录}\packages\microsoft.entityframeworkcore.tools\1.1.1\tools\EntityFrameworkCore.psd1
EntityFramework在使用Include方法时发生FormatException:该字符串未被识别为有效的布尔值。
问题原因:当数据库为mysql
时,模型中bool
类型的属性被自动映射为数据库库中tinyint(1)
类型。EF
内部将查询结果表中对应的字段转换为string
类型。调用Boolean.Parse()
抛出异常。
解决方案:表中类型强制采用bit
类型。
具体实施:在模型bool类型属性上加特性[Column(TypeName="bit")]
。
Pomelo v2.0.1在EntityFrameworkCore v2.1.0下迁移数据库抛出Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalParameterBuilder..ctor(Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)'.
错误原因:最新版EntityFrameworkCore和Pomelo不适配。
解决方案: 回退EntityFrameworkCore版本到v2.0.3.
WebApi
DELETE Request get 405 method isn't found
In IIS.
答:
- asp.net core
1.1. 添加web.config
1.2. web.config的<system.webServer>
内补充
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
- asp.net
web.config的<system.webServer>
内补充
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
asp.net core Filter
不起作用。
答:继承的子类,重写的方法记得加override
,而不是IDE自动补全的virtual
。
URL parameters in MVC 4 Web API
答:
/controller/1?p=100
public A Get(int id, int p) {}
How to get POST data in WebAPI?
答:
public async Task Post() {
dynamic obj = await Request.Content.ReadAsAsync<JObject>();
var y = obj.var1;
}
JSON
c#解析json最好的方式
答:使用dynamic
类型。
An error occurred while retrieving package metadata for 'Newtonsoft.Json.10.0.3'
答:Remove the package:
`Uninstall-Package Newtonsoft.Json -force`
Reinstall the package:
`Install-Package Newtonsoft.Json`
Or you can use 'Update-Package' :
`Update-Package Newtonsoft.Json`
Newtonsoft JSON - How to use the JsonConverter.ReadJson method to convert types when deserializing JSON
答:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
MyCustomType myCustomType = new MyCustomType();//for null values
if (reader.TokenType != JsonToken.Null)
{
if (reader.TokenType == JsonToken.StartArray)
{
JToken token = JToken.Load(reader);
List<string> items = token.ToObject<List<string>>();
myCustomType = new MyCustomType(items);
}
else
{
JValue jValue = new JValue(reader.Value);
switch (reader.TokenType)
{
case JsonToken.String:
myCustomType = new MyCustomType((string)jValue);
break;
case JsonToken.Date:
myCustomType = new MyCustomType((DateTime)jValue);
break;
case JsonToken.Boolean:
myCustomType = new MyCustomType((bool)jValue);
break;
case JsonToken.Integer:
int i = (int)jValue;
myCustomType = new MyCustomType(i);
break;
default:
Console.WriteLine("Default case");
Console.WriteLine(reader.TokenType.ToString());
break;
}
}
}
return myCustomType;
}
Newtonsoft.json custom WriteJson not execute
答:自定义转换器重写
public override bool CanWrite { get { return false; } }
Web
angular
How to get dom element in angular 2
答:
import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
ngAfterViewInit()
{
this.el.nativeElement.focus();
}