• CodeFirst 关系创建——Fluent API配置多重关系,关闭级联删除的方法


    多重性关系可以是Optional(一个属性可拥有一个单个实例或没有

    Required(一个属性必须拥有一个单个实例

    Many很多的(一个属性可以拥有一个集合或一个单个实例)。

    Has方法包括如下几个:

    • HasOptional

    • HasRequired

    • HasMany

    在多数情况还需要在Has方法后面跟随如下With方法之一:

    • WithOptional

    • WithRequired

    • WithMany

    一对多

    modelBuilder.Entity<Destination>()
    .HasMany(d => d.Lodgings)
    .WithOptional(l => l.Destination);

    Destination一对多或零对多Lodging

    如果将WithOptional改成WithRequired  这将使Lodgings必须对应一个Destination,如果删除Destination将级联删除Lodgings 详细>>

    关闭级联删除的方法:

    现在你可以设置此关系的WillCascadeOnDelete为false:

    HasRequired(l=>l.Destination)

    .WithMany(d=>d.Lodgings)

    .WillCascadeOnDelete(false)

    一对一

    modelBuilder.Entity<PersonPhoto>()

    .HasRequired(p => p.PhotoOf)

    .WithOptional(p => p.Photo);

    PersonPhoto一对零或一对一Photo

    多对多关系

    modelBuilder.Entity<Destination>()

    .HasMany(d => d.Lodgings)

    .WithRequired()

    .HasForeignKey(l => l.LocationId);

    Destination多对多Lodging

    多对多的关系语法让我比较费解。求高手解释一下

  • 相关阅读:
    set, bag, list, map的语义
    ExtJs 自定义Vtype验证
    详解.NET中的动态编译技术
    IL汇编语言介绍(译)
    C# 文件操作相关
    邮件系统
    关于Nhibernate中的多数据库支持
    .NET中 用C#操纵IIS
    ExtJS日期格式
    完全详解使用Resource实现多语言的支持
  • 原文地址:https://www.cnblogs.com/lxiang/p/2479079.html
Copyright © 2020-2023  润新知