如果你不喜歡用XML來配置,一個好的辦法是用attribute來配。這個attribute的包在sourceforge有下的,2.0版的也有了個beta的可以用,看來還是不錯的。
在SharpDevlop裏面對attribute的支持不太好,提示功能不強,VS2008要好一些,但感覺還是沒有XML好。
例子還是上次的三個關係裏面的,但這次只是給出了帶attribute的cs文件,後面有一個生成xml的代碼。
先還是1對1的例子。
- [Class]
- public class Person
- {
- public Person()
- {
- }
- [Id(0, TypeType=typeof(int))]
- [Generator(1, Class="native")]
- virtual public int ID {get; set;}
- [Property]
- virtual public int Age {get; set;}
- [Property]
- virtual public string Name {get; set;}
- [OneToOne(ClassType=typeof(Passport))]
- virtual public Passport Passport {get; set;}
- }
- [Class]
- public class Passport
- {
- public Passport()
- {
- }
- [Id(0, TypeType=typeof(int))]
- [Generator(1, Class="foreign")]
- [Param(2, Name="property", Content="Person")]
- virtual public int ID {get; set;}
- [Property]
- virtual public string Expire {get;set;}
- [OneToOne(ClassType=typeof(Person))]
- virtual public Person Person{get;set;}
- }
然後是1對多的
- [Class]
- public class Parent
- {
- public Parent()
- {
- }
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID { get; set; }
- [Set(0, Inverse = true, Lazy = true)]
- [Key(1, Column = "parent_id")]
- [OneToMany(2, ClassType = typeof(Child))]
- virtual public ISet<Child> Children { get; set; }
- }
- [Class]
- public class Parent
- {
- public Parent()
- {
- }
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID { get; set; }
- [Set(0, Inverse = true, Lazy = true)]
- [Key(1, Column = "parent_id")]
- [OneToMany(2, ClassType = typeof(Child))]
- virtual public ISet<Child> Children { get; set; }
- }
最後是多對多的
- [Class]
- public class Parent
- {
- public Parent()
- {
- }
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID { get; set; }
- [Set(0, Inverse = true, Lazy = true)]
- [Key(1, Column = "parent_id")]
- [OneToMany(2, ClassType = typeof(Child))]
- virtual public ISet<Child> Children { get; set; }
- }
- [Class]
- public class Lesson
- {
- public Lesson()
- {
- }
- [Set(0, Name="students", Table="student_lesson")]
- [Key(1, Column="student_id")]
- [ManyToMany(2, Column="lesson_id", Class="Demo5.Domain.Student, Demo5")]
- virtual public ISet<Student> students{get;set;}
- [Id(0, TypeType = typeof(int))]
- [Generator(1, Class = "native")]
- virtual public int ID{get;set;}
- virtual public string LessonName{get;set;}
- }
最後給出編譯的代碼
- [Test]
- public void TestCreateAttibute()
- {
- // TODO: Add your test.
- var stream = new MemoryStream();
- HbmSerializer.Default.Validate = true;
- HbmSerializer.Default.Serialize(stream, Assembly.GetExecutingAssembly());
- stream.Position = 0;
- for(int i=0; i < stream.Length; i++)
- Console.Write((char)stream.GetBuffer()[i]);
- stream.Position = 0;
- var cfg = new Configuration();
- cfg.Configure().AddInputStream(stream);
- new SchemaExport(cfg).Create(true, false);
- }